Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON array to PHP, Loop by index

Tags:

json

arrays

php

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.

like image 598
RobertoNovelo Avatar asked Jul 25 '26 20:07

RobertoNovelo


2 Answers

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.

like image 53
Vincent Vieira Avatar answered Jul 27 '26 11:07

Vincent Vieira


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

count($decodedjson);
like image 40
Jan Jakeš Avatar answered Jul 27 '26 11:07

Jan Jakeš



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!