0

I dont understand why my array gets cut in loop?

Array
(
    [0] => Array
        (
            [name] => order
            [value] => asd
        )

    [1] => Array
        (
            [name] => item
            [value] => aa
        )

    [2] => Array
        (
            [name] => quant
            [value] => 5
        )

    [3] => Array
        (
            [name] => price
            [value] => 20
        )

)

My php code with for loop:

for($i = 0; $i < count($json_array); $i++)
{
    echo $json_array[$i]['name'];
}

The result I'm getting is: orderitemquant but why last value price is gone? What is wrong with this code?

11
  • 2
    no error, warning on php error log? Commented Jul 13, 2012 at 12:06
  • 1
    whats the count of your array? Commented Jul 13, 2012 at 12:06
  • 2
    Are you sure $json_array is what you think it is? try printing out the array values first to make sure print_r($json_array); Commented Jul 13, 2012 at 12:07
  • 1
    I get orderitemquantprice so you are misrepresenting something. There should be no spaces in your output for instance. Are you leaving out the logic that creates the space? Commented Jul 13, 2012 at 12:12
  • 1
    I give up, if this is the complete code, I have no idea how this can be happening Commented Jul 13, 2012 at 12:33

2 Answers 2

2

Have you tried using foreach? In my opinion it suits better for iterating your array.

foreach($json_array as $sub_array) {
    echo $sub_array['name'];
}
Sign up to request clarification or add additional context in comments.

Comments

-1

Try this, off by one error:

for($i = 0; $i =< count($json_array); $i++)
{
    echo $json_array[$i]['name'];
}

2 Comments

Another answer with the same suggestion got too many negative votes and was deleted. There is no mistake in writing like the author of the question has written. It really depends on situation and there is no reason to add = sign to comparison as we are counting from zero to three. Your code counts from zero to four, which is definitely incorrect and will result in an error as $json_array[5]['name'] does not exist. Your answer is only correct if you want to count from one.
Okay sorry, you're right. I'll let it be existing here so this won't be repeated!

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.