I have string variable. It can be:
$string = '["image11.jpg"]';
Or:
$string = '["image11.jpg","image54.png"]';
Or:
$string = '["image11.jpg","image54.png"]';
Or:
$string = '["image11.jpg","image54.png","dfgr.rar"]';
And so on.
I need this variable as array, for example:
$arr[0] = 'image11.jpg';
Or:
$arr[0] = "image11.jpg";
$arr[1] = "image54.png";
Or:
$arr[0] = "image11.jpg";
$arr[1] = "image54.png";
$arr[2] = "dfgr.rar";
And so on.
Is there optimal code for that?
4 Answers
<?php
$string = '["image11.jpg","image54.png"]';
$arr=json_decode($string);
echo $arr[0];
?>
5 Comments
serg
It doesn't work on hosting server. And it works on my localhost (denwer). I don't know why...
serg
I havn't access to php.ini in my server, but if I echo phpinfo(), json is enabled (not json_decode, I don't know about json_decode).
alex
That would return an object, not an array.
Vikram Jain
Please, contact to administrator..Because here is working ..You can test online on "codepad.org"
Chaoley
According to php.net/manual/en/function.json-decode.php json_decode will return an associative array if the optional second parameter 'assoc' is true.
You can use the explode() function.
For example
$string = ' "image11.jpg","image54.png","dfgr.rar" ';
$arr = explode(',',$string); //separating string using coma ',' character
In above example, the $arr table will consists of 3 values;
$arr[0] ="image11.jpg";
$arr[1] ="image54.png";
$arr[2] ="dfgr.rar";
json_decode($str, TRUE).json_decode, there's the include-once.org/p/upgradephp polyfill to replace that function. But if your PHP version is that old, you have other problems to worry about. Don't try to reinvent a JSON parser yourself, try to fix the existing solutions if they're not working!