NOVINKA: Najžiadanejšie rekvalifikačné kurzy teraz s 50% zľavou + kurz AI ZADARMO. Nečakaj, táto ponuka dlho nevydrží! Zisti viac:

PHP - array_key_exists

Trieda

Koreň \ Bez triedy

Metóda - array_key_exists

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

The function checks whether an array contains a specified key.

For the backward compatibility's sake, the array_key_exists() function will also return true if the key is defined as a property in a given object. However, this is not the right usage of this function and the second parameter should be always an array, not an object. See the property_exists() function to check whether a property of a given object exists.

Procedurálne

Parametre

NázovDátový typPredvolená hodnotaPopis
$keymixed

The searched key.

$arrayarray

The array in which we search for the occurrence of the key.

Mávratovej hodnoty

Vracia: bool

If the array contains the given key, the function returns true, returns false otherwise.

Príklady

In the first example we have an associative array and we want to find out whether a key exists in the array.

<?php
$cars = array("Mercedes"=>"E", "Audi"=>"A6", "BMW"=>"5");

// The key "Porsche" does not exist in the array, therefore the function returns false.
$keyPorsche = "Porsche";
if (array_key_exists($keyPorsche, $cars))
    echo "Key $keyPorsche exists in the array! <br>";
else
    echo "Key $keyPorsche does not exist in the array! <br>";

// On the other hand, the key "BMW" exists in the array, therefore the function returns true.
$keyBMW = "BMW";
if (array_key_exists($keyBMW, $cars))
    echo "Key $keyBMW exists in the array! <br>";
else
    echo "Key $keyBMW does not exist in the array! <br>";

In case of an indexed array, we check the existence of an integer key.

$cars = array("Mercedes", "Audi", "BMW");

// The integer key of value 1 exists in the indexed array, therefore the function returns true.
$key1 = 1;
if (array_key_exists($key1, $cars))
    echo "Key $key1 exists in the array! <br>";
else
    echo "Key $key1 does not exist in the array! <br>";

// The array consists of 3 items, therefore the integer key 7 does not exist in the array and the function returns false.
$key2 = 7;
if (array_key_exists($key2, $cars))
    echo "Key $key2 exists in the array! <br>";
else
    echo "Key $key2 does not exist in the array! <br>";

Súvisiace manuály

      • function array_keys (array $array, mixed $search_value = null, bool $strict = false) : array
      • function in_array (mixed $needle, array $haystack, bool $strict = false) : bool
      • function isset (mixed $var, mixed $...) : bool
      Aktivity