How to convert PHP Array to JSON Object

This tutorial we will cover convert PHP array to JSON Object. JSON Objects are mainly used in API development and AJAX request. so let’s have start with example. We will give you three examples to show you.

  • Convert Numeric array to JSON
  • Convert Associative array to JSON
  • Convert Numeric array to JSON using JSON_FORCE_OBJECT parameter.

Example1

<?php    
$language = ['PHP', 'Android', 'HTML', 'JAVA', 'jQuery'];    
$output = json_encode($language);    
echo $output;
?>

Output:["PHP","Android","HTML","JAVA","jQuery"]

Example2

<?php    
$language = ['PHP' => 'Laravel', 'JS' => 'JavaScript' , 'Ajax' => 'Jquery'];    
$output= json_encode($language);    
echo $output;?>

Output:{"PHP":"Laravel","JS":"JavaScript","Ajax":"Jquery"}

Example3

<?php    
$language = ['PHP', 'Android', 'HTML', 'JAVA', 'jQuery'];    
$output= json_encode($language, JSON_FORCE_OBJECT);    
echo $output;
?>

Output:{"0":"PHP","1":"Android","2":"HTML","3":"JAVA","4":"jQuery"}

Leave a Reply