13

I have a JSON Object and I want to loop through the values:

$json = '{"1":a,"2":b,"3":c,"4":d,"5":e}';
$obj = json_decode($json, TRUE);
for($i=0; $i<count($obj['a']); $i++) {
 echo $i;
}

I want the $i to display the abcde that are the values in the object.

jrbedard
3,7345 gold badges37 silver badges35 bronze badges
asked Sep 26, 2016 at 11:51
4
  • print_r($obj) Commented Sep 26, 2016 at 11:52
  • $i<count($obj['a']) should be $i<count($obj). You want to count the total elements in the array, not the elements in the first value, which is 0 in this case. Alternatively foreach is more readable. Commented Sep 26, 2016 at 11:52
  • line 4 is thus: for($i=0; $i<count($obj); $i++) { Commented Sep 26, 2016 at 11:52
  • 2
    Your json is invalid. All alpha-characters need to be in quotes. {"1": "a", ... etc}. Commented Sep 26, 2016 at 11:54

2 Answers 2

33

Try using.

$json = '{"1":"a","2":"b","3":"c","4":"d","5":"e"}';
 $obj = json_decode($json, TRUE);
foreach($obj as $key => $value) 
{
echo 'Your key is: '.$key.' and the value of the key is:'.$value;
}
Lampe2020
3626 silver badges15 bronze badges
answered Sep 26, 2016 at 11:55

Comments

10

The shortest way to iterate it and this way you don't care about index is to use foreach like this:

foreach($obj as $value) {
 echo $value;
}

For example you don't have a index 0 in your $obj. From what I see it starts from 1. This way it's working with any index (not just numeric)

answered Sep 26, 2016 at 11:53

4 Comments

How is this different from the answer above which should also work with any $key
@Pancho It tells the reader that you don't need the key in a foreach loop and it also works without.
@Lampe2020 I understand that these answers came out at exactly the same time which is I suppose why it happened and that this one was actually first. However should timing not have been the case I stand by my comment that only one of these answers was needed - the other could just have added a comment to the first.
@Pancho Probably, yes. You've got that point.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.