PHP JSON Exercises : Get JSON representation of a value from an array
PHP JSON: Exercise-3 with Solution
Write a PHP script to get JSON representation of a value from an array.
Sample Solution:
PHP Code:
<?php
// Define an associative array with package names and versions
$arra = array("uglify-js"=> "1.3.4", "jshint"=> "0.9.1", "recess"=> "1.1.8" ,"connect"=> "2.1.3", "hogan.js"=>"2.0.0");
// Define a simple array of colors
$myarray = array('red', 'green', 'white');
// Encode the associative array into a JSON string
var_dump(json_encode($arra));
echo "\n";
// Encode the simple array into a JSON string
var_dump(json_encode($myarray));
?>
Output:
string(92) "{"uglify-js":"1.3.4","jshint":"0.9.1","recess":" 1.1.8","connect":"2.1.3","hogan.js":"2.0.0"}" string(23) "["red","green","white"]"
Explanation:
In the exercise above,
- $arra = ...: Define an associative array with package names as keys and their versions as values.
- $myarray = ...: Define a simple array containing color names.
- json_encode($arra): Encode the associative array into a JSON string.
- var_dump(...): Output the JSON-encoded string for debugging purposes.
- echo "\n";: Print a newline character for better readability in the output.
- Repeat steps 3-5 for the simple array '$myarray'.
Flowchart :
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a PHP script to decode large integers.
Next: Write a PHP function to display JSON decode errors.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/php-exercises/php-json-exercise-3.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics