What is the second array_keys parameter for?


I was giving a stir in the sublime text and I came across something I did not expect when I typed the function array_keys

 array_keys(arg, search_value, strict);

I did the test and the second parameter actually works.

What is the purpose of it, anyway?

asked by anonymous 02.12.2015 / 17:32

4 answers


The second parameter causes the function to return the index of the positions where a value is found.

For example:

$array = array("teste", "algo", "outra coisa", "teste", "teste");
var_dump(array_keys($array, "teste"));

Will return the following:

array(3) {

Because the name "test" is present in positions 0, 3 and 4 of the array.

I submitted a demo link

02.12.2015 / 17:38

array_keys () , returns all the keys in an array. When the second argument is reported it returns all occurrences of that value, it looks like a version that returns multiple values of array_search ( ) .

$arr = array("blue", "red", "green", "blue", "blue");
echo '<pre>';
print_r(array_keys($arr, "blue"));//retorna uma array com 0,3,4

$key = array_search("blue", $arr);
echo "<pre>";
print_r($key);//retorna apenas 0
02.12.2015 / 17:40

Serves to filter the indexes that will be returned - According to the documentation

Parameters ¶




An array containing keys to return.




If specified, then only keys containing these values are returned.




In PHP 5, this parameter determines whether the comparison is rigid (===) during the search.

02.12.2015 / 17:39

By what I understand it returns only the values you specify, thus serving as an even search option, as the name suggests. '


That is, in this example it will only show the results containing the Highlander value, so it would serve as a strpos , only returning the values without need to go through the array.

02.12.2015 / 17:43