0

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?

8
  • 6
    json_decode($str, TRUE). Commented Nov 1, 2012 at 9:18
  • Did you come up with that format yourself or is that JSON? Commented Nov 1, 2012 at 9:19
  • json from javascript (jquery, ajax) Commented Nov 1, 2012 at 9:20
  • 1
    possible duplicate of How to decode a JSON string in PHP? Commented Nov 1, 2012 at 9:21
  • 1
    Worst case, should your production server be running such an old version of PHP that it doesn't come with 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! Commented Nov 1, 2012 at 9:33

4 Answers 4

2
<?php

$string = '["image11.jpg","image54.png"]';
$arr=json_decode($string);
echo $arr[0];
?>
Sign up to request clarification or add additional context in comments.

5 Comments

It doesn't work on hosting server. And it works on my localhost (denwer). I don't know why...
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).
That would return an object, not an array.
Please, contact to administrator..Because here is working ..You can test online on "codepad.org"
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.
2

use json_decode for make this string to array

$arr = json_decode($string,true)

thanks

Comments

-2
preg_match_all('@"(.*?)"@',$string,$arr);

Comments

-2

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

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.