3

thanks for your time:

First of all I have the following Json string

$jsonarr = '["somestring1", "somestring2","somestring3"]'

which I want to convert to a PHP array

$decodedjson = json_decode($jsonarr,TRUE);

and then iterate through all of the members of the array, something such as :

for ($i=0;$i<3;$i++)
{
    echo $decodedjson[$i];
}

First of all, is it possible to get the length of this array?

Second, this code throws an error. I am not sure where I am doing it wrong.

Thank you for your time.

5
  • Could you share error message Commented Oct 25, 2013 at 21:00
  • You can get the length with count($decodedjson), just like any other array. Commented Oct 25, 2013 at 21:00
  • var_dump($decodedjson) to see what it contains. Commented Oct 25, 2013 at 21:01
  • I tried your code, it worked fine once I added the semicolon on the first assignment. Commented Oct 25, 2013 at 21:01
  • You need to post your error. PHP < 5.2 does not have json_decode(), which is a not-uncommon scenario on shared hosting or Red Hat 5 systems running PHP 5.1. Commented Oct 25, 2013 at 21:02

4 Answers 4

1

If the array returned by json_decode() is valid, yes. You just need to call :

 count($decodedjson);

But first, try to do a var_dump of $decodedjson. You'll see how it is decoded. If it's equals to null, so the json_decode() call failed. You can grab the error code with json_last_error() (list of error codes : http://php.net/manual/en/function.json-last-error.php)

If you want to go faster, and iterate through the array without knowing the length, you just have to use foreach instead of for loop.

And yeah, like Akshay said, share the error you're getting. Good luck with that.

Sign up to request clarification or add additional context in comments.

Comments

1

The only error I see is a missing semicolon on the first line. You can get the length like this:

count($decodedjson);

Comments

1

Yes you can get the array length by count() function like below :

$jsonarr = '["somestring1", "somestring2","somestring3"]' ;
$decodedjson = json_decode($jsonarr);

for ($i=0;$i < count($decodedjson);$i++) 
{
    echo $decodedjson[$i] . '<br>';
}

Comments

0

As always you can use foreach to iterate through objects/arrays:

foreach ($decodedjson as $key => $value) {
    echo $key . ' => ' .$value;
}

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.