views:

133

answers:

2
$array = ( 
    array('1231415'=>array('foo'=>'bar', 'test'=> 1)),
    array('32434'=>array('foo'=>'bar', 'test'=> '0')),
    array('123244'=>array('foo'=>'bar', 'test'=> 0)),
    array('193928'=>array('foo'=>'bar', 'test'=> 1))
);

I have an array that has (many) random keys, the ID number. I need to test each array within if 'test' = 1, and so I made a foreach loop.

foreach ($array as $sub) {
  if ($sub['test'] == '1' ) {
     echo 'User: ' . $sub . ' has test = 1';
  }
}

This works, but it returns 'User: Array has test = 1'

How on earth to I get which ID number, (that random number) has test=1 in it?

I tried doing $array as $sub=>$value, but for some reason it just makes the foreach not work. Thank you!

+10  A: 

Use this foreach syntax instead:

foreach ($array as $key => $sub) {
  if ($sub['test'] == '1' ) {
    echo 'User: ' . $key . ' has test = 1';
  }
}

This assumes that the data is in the form:

$array = array(
  '1234' => array('test' => 1),
  '5678' => array('test' => 2)
);

If you need to keep your data as it is now, you'll need to use something more like:

foreach ($array as $item) {
  list($key, $info) = $item;
  if ($info['test'] == 1) {
    echo 'User: ' . $key . ' has test = 1';
  }
}
pix0r
this isn't actually correct, considering the array structure he has here.
nickf
You're right - I've updated it both with an alternate data format and with a solution that will match the current data format.
pix0r
@pix0r: Your 3rd code snippet won't work for him because his array definition has a syntax error.
Asaph
Hah, ok.. he needs to add an `array` on the first line before the first open paren.
pix0r
+3  A: 

There are 2 problems with your code.

1) Your array declaration is slightly messed up. Try this:

$array = array( 
   '1231415'=>array('foo'=>'bar', 'test'=> 1),
   '32434'=>array('foo'=>'bar', 'test'=> 0),
   '123244'=>array('foo'=>'bar', 'test'=> 0),
   '193928'=>array('foo'=>'bar', 'test'=> 1)
);

2) In your foreach, you're losing the id key. Try this:

foreach ($array as $id => $sub) {
    if ($sub['test'] == 1) {
        echo "User: " . $id . " has test = 1\n";
    }
}

In my test the above outputs:

User: 1231415 has test = 1
User: 193928 has test = 1
Asaph