Author: Admin/Publisher |finished | checked
PHP array_keys function
PHP array_keys function returns all the keys in a new array; this will be an indexed array. If you use $search_value in the parameters, it will return an array that contains a subset of keys with that value.
array_keys(array $array): array
array_keys(array $array, mixed $search_value, bool $strict = false): arraySintaxis / Sintax
$narray = array_keys($array_proporcinado);
Parameters
$array – The array that we provide.
$search_value – If this parameter is specified, the returned array will contain only keys that have this value.
$strict – Determines whether to use strict comparison (===).
Return
It will return an array with all the keys from the provided array.
Examples of PHP array_keys function
Suppose we have this multidimensional array taken from an SQL query. In this case, we cannot directly use array_keys on our $users array, but we can use it on one of its elements.
$users = array(
array(
'nombre' => 'Juan Pérez',
'edad' => 25,
'email' => 'juan@example.com',
),
array(
'nombre' => 'María Rodríguez',
'edad' => 30,
'email' => 'maria@example.com',
),
array(
'nombre' => 'Carlos Sánchez',
'edad' => 22,
'email' => 'carlos@example.com',
),
array(
'nombre' => 'Luis González',
'edad' => 28,
'email' => 'luis@example.com',
),
array(
'nombre' => 'Ana Martínez',
'edad' => 35,
'email' => 'ana@example.com',
),
array(
'nombre' => 'Laura López',
'edad' => 29,
'email' => 'laura@example.com',
),
array(
'nombre' => 'Pedro Torres',
'edad' => 27,
'email' => 'pedro@example.com',
),
array(
'nombre' => 'Elena Ramírez',
'edad' => 31,
'email' => 'elena@example.com',
),
array(
'nombre' => 'Sofía García',
'edad' => 26,
'email' => 'sofia@example.com',
),
array(
'nombre' => 'Mario Díaz',
'edad' => 24,
'email' => 'mario@example.com',
),
array(
'nombre' => 'Javier Fernández',
'edad' => 33,
'email' => 'javier@example.com',
),
array(
'nombre' => 'Isabel Ortega',
'edad' => 23,
'email' => 'isabel@example.com',
),
array(
'nombre' => 'Rosa Jiménez',
'edad' => 32,
'email' => 'rosa@example.com',
),
array(
'nombre' => 'Diego Silva',
'edad' => 28,
'email' => 'diego@example.com',
),
array(
'nombre' => 'Carolina Castro',
'edad' => 34,
'email' => 'carolina@example.com',
),
);
print_r(array_keys($users[0]));
Array
(
[0] => nombre
[1] => edad
[2] => email
)
Let’s see an example from php.net
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));
$array = array("color" => array("blue", "red", "green"),
"size" => array("small", "medium", "large"));
print_r(array_keys($array));
Array
(
[0] => 0
[1] => color
)
Array
(
[0] => 0
[1] => 3
[2] => 4
)
Array
(
[0] => color
[1] => size
)
Category: en-php
Something wrong?
If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.

