-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

3
  • go to php array w3 or google it Commented Feb 21, 2018 at 4:23
  • Take a look at associative arrays in PHP. It looks like that's what you need Commented Feb 21, 2018 at 4:24
  • 1
    Your answer is here: w3schools.com/php/showphp.asp?filename=demo_array_assoc Commented Feb 21, 2018 at 4:24

4 Answers 4

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"
}
Sign up to request clarification or add additional context in comments.

1 Comment

json_decode() has a flag that will cast the data as an array.
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'];

1 Comment

fount the solution at this link stackoverflow.com/questions/15966693/… ,
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

Comments

-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"];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.