-1

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

sorak
  • 2,607
  • 2
  • 16
  • 24

4 Answers4

2

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"
}
sorak
  • 2,607
  • 2
  • 16
  • 24
1

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'];
Sudheesh Singanamalla
  • 2,283
  • 3
  • 19
  • 36
  • fount the solution at this link https://stackoverflow.com/questions/15966693/explode-into-key-value-pair , – sudaila Feb 21 '18 at 04:31
1

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.

https://stackoverflow.com/a/18576902/5546916

ks1bbk
  • 31
  • 2
-1

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"];
Param Bhat
  • 470
  • 1
  • 6
  • 17