What is the second parameter of array_keys for?

Asked

Viewed 352 times

7

I was stirring the sublime text and I came across something I didn’t expect when I went to type the function array_keys

 array_keys(arg, search_value, strict);

I did the test and really the second parameter works.

What is his purpose, after all?

  • 1

    The second parameter wouldn’t work pq? pq is php, vc ta zoando xD?

  • 1

    +1 for the sublime

  • 1

    I used this command last week. And the array_key_exists also.

4 answers

5


The second parameter returns the index of the positions where a given value is.

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 the positions 0, 3 and 4 of the array.

I put a demonstration https://3v4l.org/MWBAi

4

array_keys(), returns all keys of an array. When second argument is informed it returns all occurrences of that value, it seems to me 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

2

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

Parameters

input

An array containing keys to be returned.

search_value

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

Strict

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

2

From what I understand it returns only the values you specify, serving as well 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 that contain the value "Highlander", Therefore it would serve as a strpos, but already returning the values without having to go through the array.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.