Chose Language:
comments
Author: Admin/Publisher |finished | checked

PHP key function

The PHP key function retrieves the key of an array. This key or key is the one of the element to which the array is pointing, being the internal pointer.

Description / Descripción
(array|object $array): int|string|null

Something we should highlight is that we should use other PHP array functions for this to make sense, otherwise, we will get the same key every time since it will be pointing to the first element.

We have to add something else, and that is that calling objects is deprecated.

Parameters

$array – the array from which we want to get the key.

Returns

int – if it is an indexed or numeric array we will get its index.

string – if the array is an associative array

null – if you are pointing outside the range of the array

Examples

Let’s see the first example, in this one we will move the pointer box by box with the next function until we go out of range:

Comprendiendo la funcion key()
//blastcoding.com
$articulosEscolares = ["Cuaderno", "Lápiz", "Mochila", "Regla"];
echo key($articulosEscolares)."\n";
next($articulosEscolares);
echo key($articulosEscolares)."\n";
next($articulosEscolares);
echo key($articulosEscolares)."\n";
next($articulosEscolares);
echo key($articulosEscolares)."\n";
next($articulosEscolares);
echo "out of range:". key($articulosEscolares)."\n";
var_dump(key($articulosEscolares));
0
1
2
3
out of range:
NULL

Let’s see the example from php.net

Este es un ejemplo de php.net
<?php
$array = array(
    'fruit1' => 'apple',
    'fruit2' => 'orange',
    'fruit3' => 'grape',
    'fruit4' => 'apple',
    'fruit5' => 'apple');

// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
    if ($fruit_name == 'apple') {
        echo key($array), "\n";
    }
    next($array);
}
?>
fruit1
fruit4
fruit5
Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category

Comments