Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach: Get All The 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 the keys that have the value "a".

I know I can get them using a while loop:

while ($a = current($array)) {
    if ($a == 'a') {
        echo key($array).',';
    }
    next($array);
}

How can I get them using a foreach loop instead?

I've tried:

   foreach ($array as $a) {
        if ($a == 'a') {
            echo key($array).',';
        }

    }

and I got

1,1,1,

as the result.


2 Answers

If you would like all of the keys for a particular value, I would suggest using array_keys, using the optional search_value parameter.

$input = array("Foo" => "X", "Bar" => "X", "Fizz" => "O");
$result = array_keys( $input, "X" );

Where $result becomes

Array ( 
  [0] => Foo 
  [1] => Bar 
)

If you wish to use a foreach, you can iterate through each key/value set, adding the key to a new array collection 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 
)
like image 137
Sampson Avatar answered Dec 01 '25 18:12

Sampson


You can use the below to print out keys with specific value


foreach ($array as $key=>$val) {
        if ($val == 'a') {
            echo $key." ";
        }

    }

like image 43
balanv Avatar answered Dec 01 '25 19:12

balanv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!