Foreach: get all keys that have the value "X"
Suppose I have an array like this:
$array = array("a","b","c","d","a","a");
and I want to get all keys that have the value "a".
I know I can use them with a loop while
:
while ($a = current($array)) {
if ($a == 'a') {
echo key($array).',';
}
next($array);
}
How can I use them instead of a loop foreach
?
I tried:
foreach ($array as $a) {
if ($a == 'a') {
echo key($array).',';
}
}
and i got
1,1,1,
...
If you want to use all keys for a specific value, I would suggest using array_keys
using an optional parameter search_value
.
$input = array("Foo" => "X", "Bar" => "X", "Fizz" => "O");
$result = array_keys( $input, "X" );
Where $result
becomes
Array (
[0] => Foo
[1] => Bar
)
If you want to use foreach
, you can iterate over each key / value set by adding the key to a new collection of the array when its value matches your search:
$array = array("a","b","c","d","a","a");
$keys = array();
foreach ( $array as $key => $value )
$value === "a" && array_push( $keys, $key );
Where $keys
becomes
Array (
[0] => 0
[1] => 4
[2] => 5
)
source to share