Php checking array key exists

Php checking array key exists

  • Different ways to write a PHP code
  • How to write comments in PHP ?
  • Introduction to Codeignitor (PHP)
  • How to echo HTML in PHP ?
  • Error handling in PHP
  • How to show All Errors in PHP ?
  • How to Start and Stop a Timer in PHP ?
  • How to create default function parameter in PHP?
  • How to check if mod_rewrite is enabled in PHP ?
  • Web Scraping in PHP Using Simple HTML DOM Parser
  • How to pass form variables from one page to other page in PHP ?
  • How to display logged in user information in PHP ?
  • How to find out where a function is defined using PHP ?
  • How to Get $_POST from multiple check-boxes ?
  • How to Secure hash and salt for PHP passwords ?
  • Program to Insert new item in array on any position in PHP
  • PHP append one array to another
  • How to delete an Element From an Array in PHP ?
  • How to print all the values of an array in PHP ?
  • How to perform Array Delete by Value Not Key in PHP ?
  • Removing Array Element and Re-Indexing in PHP
  • How to count all array elements in PHP ?
  • How to insert an item at the beginning of an array in PHP ?
  • PHP Check if two arrays contain same elements
  • Merge two arrays keeping original keys in PHP
  • PHP program to find the maximum and the minimum in array
  • How to check a key exists in an array in PHP ?
  • PHP | Second most frequent element in an array
  • Sort array of objects by object fields in PHP
  • PHP | Sort array of strings in natural and standard orders
  • How to pass PHP Variables by reference ?
  • How to format Phone Numbers in PHP ?
  • How to use php serialize() and unserialize() Function
  • Implementing callback in PHP
  • PHP | Merging two or more arrays using array_merge()
  • PHP program to print an arithmetic progression series using inbuilt functions
  • How to prevent SQL Injection in PHP ?
  • How to extract the user name from the email ID using PHP ?
  • How to count rows in MySQL table in PHP ?
  • How to parse a CSV File in PHP ?
  • How to generate simple random password from a given string using PHP ?
  • How to upload images in MySQL using PHP PDO ?
  • How to check foreach Loop Key Value in PHP ?
  • How to properly Format a Number With Leading Zeros in PHP ?
  • How to get a File Extension in PHP ?
  • How to get the current Date and Time in PHP ?
  • PHP program to change date format
  • How to convert DateTime to String using PHP ?
  • How to get Time Difference in Minutes in PHP ?
  • Return all dates between two dates in an array in PHP
  • Sort an array of dates in PHP
  • How to get the time of the last modification of the current page in PHP?
  • How to convert a Date into Timestamp using PHP ?
  • How to add 24 hours to a unix timestamp in php?
  • Sort a multidimensional array by date element in PHP
  • Convert timestamp to readable date/time in PHP
  • PHP | Number of week days between two dates
  • PHP | Converting string to Date and DateTime
  • How to get last day of a month from date in PHP ?
  • PHP | Change strings in an array to uppercase
  • How to convert first character of all the words uppercase using PHP ?
  • How to get the last character of a string in PHP ?
  • How to convert uppercase string to lowercase using PHP ?
  • How to extract Numbers From a String in PHP ?
  • How to replace String in PHP ?
  • How to Encrypt and Decrypt a PHP String ?
  • How to display string values within a table using PHP ?
  • How to write Multi-Line Strings in PHP ?
  • How to check if a String Contains a Substring in PHP ?
  • How to append a string in PHP ?
  • How to remove white spaces only beginning/end of a string using PHP ?
  • How to Remove Special Character from String in PHP ?
  • How to create a string by joining the array elements using PHP ?
  • How to prepend a string in PHP ?
Читайте также:  Find errors in javascript code

Источник

array_key_exists

array_key_exists() returns true if the given key is set in the array. key can be any value possible for an array index.

Parameters

An array with keys to check.

Return Values

Returns true on success or false on failure.

Note:

array_key_exists() will search for the keys in the first dimension only. Nested keys in multidimensional arrays will not be found.

Examples

Example #1 array_key_exists() example

$search_array = array( ‘first’ => 1 , ‘second’ => 4 );
if ( array_key_exists ( ‘first’ , $search_array )) echo «The ‘first’ element is in the array» ;
>
?>

Example #2 array_key_exists() vs isset()

isset() does not return true for array keys that correspond to a null value, while array_key_exists() does.

$search_array = array( ‘first’ => null , ‘second’ => 4 );

// returns false
isset( $search_array [ ‘first’ ]);

// returns true
array_key_exists ( ‘first’ , $search_array );
?>

Notes

Note:

For backward compatibility reasons, array_key_exists() will also return true if key is a property defined within an object given as array . This behaviour is deprecated as of PHP 7.4.0, and removed as of PHP 8.0.0.

To check whether a property exists in an object, property_exists() should be used.

See Also

  • isset() — Determine if a variable is declared and is different than null
  • array_keys() — Return all the keys or a subset of the keys of an array
  • in_array() — Checks if a value exists in an array
  • property_exists() — Checks if the object or class has a property

User Contributed Notes 3 notes

When you want to check multiple array keys:

$array = [];
$array [ ‘a’ ] = » ;
$array [ ‘b’ ] = » ;
$array [ ‘c’ ] = » ;
$array [ ‘d’ ] = » ;
$array [ ‘e’ ] = » ;

// all given keys a,b,c exists in the supplied array
var_dump ( array_keys_exists ([ ‘a’ , ‘b’ , ‘c’ ], $array )); // bool(true)

function array_keys_exists (array $keys , array $array ): bool
$diff = array_diff_key ( array_flip ( $keys ), $array );
return count ( $diff ) === 0 ;
>

In PHP7+ to find if a value is set in a multidimensional array with a fixed number of dimensions, simply use the Null Coalescing Operator: ??

So for a three dimensional array where you are not sure about any of the keys actually existing

// use:
$exists = array_key_exists ( $key3 , $arr [ $key1 ][ $key2 ]??[]) ;

I took hours for me to debug, and I finally recognized that,

You have to reset the $array before using array_key_exists
reset($array);
array_key_exists($needle,$array);

  • Array Functions
    • array_​change_​key_​case
    • array_​chunk
    • array_​column
    • array_​combine
    • array_​count_​values
    • array_​diff_​assoc
    • array_​diff_​key
    • array_​diff_​uassoc
    • array_​diff_​ukey
    • array_​diff
    • array_​fill_​keys
    • array_​fill
    • array_​filter
    • array_​flip
    • array_​intersect_​assoc
    • array_​intersect_​key
    • array_​intersect_​uassoc
    • array_​intersect_​ukey
    • array_​intersect
    • array_​is_​list
    • array_​key_​exists
    • array_​key_​first
    • array_​key_​last
    • array_​keys
    • array_​map
    • array_​merge_​recursive
    • array_​merge
    • array_​multisort
    • array_​pad
    • array_​pop
    • array_​product
    • array_​push
    • array_​rand
    • array_​reduce
    • array_​replace_​recursive
    • array_​replace
    • array_​reverse
    • array_​search
    • array_​shift
    • array_​slice
    • array_​splice
    • array_​sum
    • array_​udiff_​assoc
    • array_​udiff_​uassoc
    • array_​udiff
    • array_​uintersect_​assoc
    • array_​uintersect_​uassoc
    • array_​uintersect
    • array_​unique
    • array_​unshift
    • array_​values
    • array_​walk_​recursive
    • array_​walk
    • array
    • arsort
    • asort
    • compact
    • count
    • current
    • end
    • extract
    • in_​array
    • key_​exists
    • key
    • krsort
    • ksort
    • list
    • natcasesort
    • natsort
    • next
    • pos
    • prev
    • range
    • reset
    • rsort
    • shuffle
    • sizeof
    • sort
    • uasort
    • uksort
    • usort
    • each

    Источник

    array_key_exists

    Функция array_key_exists() возвращает TRUE , если в массиве присутствует указанный ключ key . Параметр key может быть любым значением, которое подходит для индекса массива.

    Список параметров

    Массив с проверяемыми ключами

    Возвращаемые значения

    Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

    Примеры

    Пример #1 Пример использования array_key_exists()

    $search_array = array( ‘first’ => 1 , ‘second’ => 4 );
    if ( array_key_exists ( ‘first’ , $search_array )) echo «Массив содержит элемент ‘first’.» ;
    >
    ?>

    Пример #2 array_key_exists() и isset()

    isset() не возвращает TRUE для ключей массива, указывающих на NULL , а array_key_exists() возвращает.

    $search_array = array( ‘first’ => null , ‘second’ => 4 );

    // возвращает false
    isset( $search_array [ ‘first’ ]);

    // возвращает true
    array_key_exists ( ‘first’ , $search_array );
    ?>

    Примечания

    Замечание:

    Для обратной совместимости может быть использован следующий устаревший псевдоним: key_exists()

    Замечание:

    По причинам обратной совместимости array_key_exists() возвращает TRUE , если key является свойством объекта, переданным в качестве параметра array . На это поведение не стоит полагаться, и перед использованием данной функции необходимо проверять, что параметр array имеет тип array .

    Чтобы проверить, содержит ли объект какое-либо свойство, используйте функцию property_exists() .

    Смотрите также

    • isset() — Определяет, была ли установлена переменная значением отличным от NULL
    • array_keys() — Возвращает все или некоторое подмножество ключей массива
    • in_array() — Проверяет, присутствует ли в массиве значение
    • property_exists() — Проверяет, содержит ли объект или класс указанный атрибут

    Источник

    key_exists

    Функция является псевдонимом: array_key_exists() .

    User Contributed Notes

    • Функции для работы с массивами
      • array_​change_​key_​case
      • array_​chunk
      • array_​column
      • array_​combine
      • array_​count_​values
      • array_​diff_​assoc
      • array_​diff_​key
      • array_​diff_​uassoc
      • array_​diff_​ukey
      • array_​diff
      • array_​fill_​keys
      • array_​fill
      • array_​filter
      • array_​flip
      • array_​intersect_​assoc
      • array_​intersect_​key
      • array_​intersect_​uassoc
      • array_​intersect_​ukey
      • array_​intersect
      • array_​is_​list
      • array_​key_​exists
      • array_​key_​first
      • array_​key_​last
      • array_​keys
      • array_​map
      • array_​merge_​recursive
      • array_​merge
      • array_​multisort
      • array_​pad
      • array_​pop
      • array_​product
      • array_​push
      • array_​rand
      • array_​reduce
      • array_​replace_​recursive
      • array_​replace
      • array_​reverse
      • array_​search
      • array_​shift
      • array_​slice
      • array_​splice
      • array_​sum
      • array_​udiff_​assoc
      • array_​udiff_​uassoc
      • array_​udiff
      • array_​uintersect_​assoc
      • array_​uintersect_​uassoc
      • array_​uintersect
      • array_​unique
      • array_​unshift
      • array_​values
      • array_​walk_​recursive
      • array_​walk
      • array
      • arsort
      • asort
      • compact
      • count
      • current
      • end
      • extract
      • in_​array
      • key_​exists
      • key
      • krsort
      • ksort
      • list
      • natcasesort
      • natsort
      • next
      • pos
      • prev
      • range
      • reset
      • rsort
      • shuffle
      • sizeof
      • sort
      • uasort
      • uksort
      • usort
      • each

      Источник

Оцените статью