I have a string = "Name":"Susan","Age":"23","Gender":"Male";
How to store them in an array so that I can echo the value for example:
echo $array['Name']
or
echo $array['Age']
Thanks
I have a string = "Name":"Susan","Age":"23","Gender":"Male";
How to store them in an array so that I can echo the value for example:
echo $array['Name']
or
echo $array['Age']
Thanks
If your string is already:
"Name":"Susan","Age":"23","Gender":"Male"
That's almost JSON, so you can just enclose it in curly brackets and convert it to turn that into an array:
$decoded = (Array)json_decode('{'.$str.'}');
json_decode()
normally outputs an object, but here we're casting it to an array. This is not required, but it changes how you have to access the resulting elements.
This would render the following associative array:
array(3) {
["Name"]=>
string(5) "Susan"
["Age"]=>
string(2) "23"
["Gender"]=>
string(4) "Male"
}
Associative Arrays in PHP are what you need to achieve your task. In PHP array()
are actually ordered maps i.e. associates values
with a key
Here is an example. An associative array is an array where each key has its own specific value. Here's an example.
$values = array("Name"=>"Susan", "Age"=>"23", "Gender"=>"Male");
echo $values['Name'];
echo $values['Age'];
echo $values['Gender'];
You can store string as json
$json = '{"Name":"Susan","Age":"23","Gender":"Male"}';
$array = json_decode($json, true);
var_dump($array);
The manual specifies the second argument of json_decode as:
assoc When TRUE, returned objects will be converted into associative arrays.
Try below snippet
$string = "Name":"Susan","Age":"23","Gender":"Male";
//explode string with `,` first
$s = explode(",",$string); // $s[0] = "Name":"Susan"....
$array = array();
foreach($s as $data){
$t = array();
$t = explode(":",$data); //explode with `:`
$array[$t[0]] = $t[1];
}
echo $array["name"];