What is the second array_keys parameter for?

7

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

5

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) {
  [0]=>
  int(0)
  [1]=>
  int(3)
  [2]=>
  int(4)
}

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
4

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 ( ) .

<?php
$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
2

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

Parameters ¶

  

input

     

An array containing keys to return.

     

search_value

     

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

     

strict

     

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

    
02.12.2015 / 17:39
2

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

<?php
   $a=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander");
   print_r(array_keys($a,"Highlander"));
?>

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