$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!
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';
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With