Home »
        PHP »
        PHP programs
    
    PHP program to decode the JSON string into an associative array
    
    
    
    
	    Here, we are going to learn how to decode the JSON string into an associative array in PHP?
	    
		    Submitted by Nidhi, on November 23, 2020 [Last updated : March 13, 2023]
	    
    
    
    Decoding JSON String into an Associative Array
    Here, we will convert a JSON string into an associative array using the json_decode() function and print the elements of the associative array on the webpage.
    PHP code to decode the JSON string into an associative array
    The source code to decode the JSON string into an associative array is given below. The given program is compiled and executed successfully.
<?php
//PHP program to decode the Json string into 
//associative array.
$json = '{"Id1":101,"Id2":102,"Id3":103,"Id4":104}';
$ids = json_decode($json);
foreach ($ids as $key => $value)
{
    print ("Key: " . $key . " Value: " . $value . "<br/>");
}
?>
Output
Key: Id1 Value: 101
Key: Id2 Value: 102
Key: Id3 Value: 103
Key: Id4 Value: 104
    Explanation
    Here, we converted the JSON string into an associative array using library function json_decode() and assigned the result into $ids variable.
foreach($ids as $key => $value) 
{  
    print("Key: ".$key." Value: ".$value."
");  
}  
    Here, we printed the key and values of the associative array using the foreach loop on the webpage.
    PHP JSON Programs »
	
    
    
    
	
	
    
    
  
    Advertisement
    
    
    
  
  
    Advertisement