0

Hey guys I have an array like this

print_r($grouparray);

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => new group 1
            [2] => 100
            [3] => 1000
            [4] => group description
            [5] => #000000
        )

    [1] => Array
        (
            [0] => 2
            [1] => new group 2
            [2] => 1000
            [3] => 2000
            [4] => group description
            [5] => #ff0000
        )

)

Now I'm only allowed to write a foreach statement and I did this :

        foreach ((array)$grouparray AS $groups => $group) {
            echo $group[1]."<br>";
        }

and I expect output to be like this :

 new group 1
 new group 2

but the output is null.

2
  • Why are you casting to (array) in the foreach? Commented Dec 25, 2011 at 8:25
  • because its a template engine syntax; and It only allows to use arrays in foreach with array() mark Commented Dec 25, 2011 at 8:29

3 Answers 3

3

It works for me:

$grouparray [] = array (
    1, 'new group 1', description); 

$grouparray [] = array (
    2, 'new group 2', description); 


print_r($grouparray);

foreach ($grouparray as $groups=>$group) {
    echo $group[1]."\r\n";
}

Output is:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => new group 1
            [2] => description
        )

    [1] => Array
        (
            [0] => 2
            [1] => new group 2
            [2] => description
        )

)
new group 1
new group 2

My opinoin is that "new group 1" is not assigned by you to any object. Check it!

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

1 Comment

yeah thanks , I was correct and you were right the row was not assigned so I got null output. that was so stupid , i should get some rest
2
foreach ($grouparray as $group) {
    echo $group[1] . "<br />";
}

Comments

1

There are some things to correct in your code:

  1. You don't need the tpye casting for your array, it is already an array.
  2. Since you are looking for the values, and not the keys, you can omit that.

This gives us the following code:

foreach ($grouparray as $group) {
    echo $group[1] . "<br />";
}

3 Comments

thanks but have you noticed that the array is a two level loop ? first one is the overall groups and the other one is each group details !
In which case you would loop $group normally as your would with any other array.
believe me I didn't know that, and I thought the two level array should have a => for more specification.

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.