$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';
}
}
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
";
}
}
In my test the above outputs:
User: 1231415 has test = 1
User: 193928 has test = 1