Php проверить наличие элементов массива

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

    Источник

    in_array

    Ищет в haystack значение needle . Если strict не установлен, то при поиске будет использовано нестрогое сравнение.

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

    Замечание:

    Если needle — строка, сравнение будет произведено с учетом регистра.

    Если третий параметр strict установлен в TRUE тогда функция in_array() также проверит соответствие типов параметра needle и соответствующего значения массива haystack .

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

    Возвращает TRUE , если needle был найден в массиве, и FALSE в обратном случае.

    Примеры

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

    $os = array( «Mac» , «NT» , «Irix» , «Linux» );
    if ( in_array ( «Irix» , $os )) echo «Нашел Irix» ;
    >
    if ( in_array ( «mac» , $os )) echo «Нашел mac» ;
    >
    ?>

    Второго совпадения не будет, потому что in_array() регистрозависима, таким образом, программа выведет:

    Пример #2 Пример использования in_array() с параметром strict

    if ( in_array ( ‘12.4’ , $a , true )) echo «‘12.4’ найдено со строгой проверкой\n» ;
    >

    if ( in_array ( 1.13 , $a , true )) echo «1.13 найдено со строгой проверкой\n» ;
    >
    ?>

    Результат выполнения данного примера:

    1.13 найдено со строгой проверкой

    Пример #3 Пример использования in_array() с массивом в качестве параметра needle

    if ( in_array (array( ‘p’ , ‘h’ ), $a )) echo «‘ph’ найдено\n» ;
    >

    if ( in_array (array( ‘f’ , ‘i’ ), $a )) echo «‘fi’ найдено\n» ;
    >

    if ( in_array ( ‘o’ , $a )) echo «‘o’ найдено\n» ;
    >
    ?>

    Результат выполнения данного примера:

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

    • array_search() — Осуществляет поиск данного значения в массиве и возвращает соответствующий ключ в случае удачи
    • isset() — Определяет, была ли установлена переменная значением отличным от NULL
    • array_key_exists() — Проверяет, присутствует ли в массиве указанный ключ или индекс

    Источник

    PHP in_array

    Summary: in this tutorial, you will learn how to use the PHP in_array() function to check if a value exists in an array.

    Introduction to the PHP in_array() function

    The in_array() function returns true if a value exists in an array. Here’s the syntax of the in_array() function:

    in_array ( mixed $needle , array $haystack , bool $strict = false ) : boolCode language: PHP (php)
    • $needle is the searched value.
    • $haystack is the array to search.
    • $strict if the $strict sets to true , the in_array() function will use the strict comparison.

    The in_array() function searches for the $needle in the $haystack using the loose comparison ( == ). To use the strict comparison ( === ), you need to set the $strict argument to true .

    If the value to check is a string, the in_array() function will search for it case-sensitively.

    The in_array() function returns true if the $needle exists in the $array ; otherwise, it returns false .

    PHP in_array() function examples

    Let’s take some examples of using the in_array() function.

    1) Simple PHP in_array() function examples

    The following example uses the in_array() function to check if the value ‘update’ is in the $actions array:

     $actions = [ 'new', 'edit', 'update', 'view', 'delete', ]; $result = in_array('update', $actions); var_dump($result); // bool(true)Code language: HTML, XML (xml)

    The following example returns false because the publish value doesn’t exist in the $actions array:

     $actions = [ 'new', 'edit', 'update', 'view', 'delete', ]; $result = in_array('publish', $actions); var_dump($result); // bool(false) Code language: HTML, XML (xml)

    The following example returns false because the value ‘New’ doesn’t exist in the $actions array. Note that the in_array() compares the strings case-sensitively:

     $actions = [ 'new', 'edit', 'update', 'view', 'delete', ]; $result = in_array('New', $actions); var_dump($result); // bool(false) Code language: HTML, XML (xml)

    2) Using PHP in_array() function with the strict comparison example

    The following example uses the in_array() function to find the number 15 in the $user_ids array. It returns true because the in_array() function compares the values using the loose comparison ( == ):

     $user_ids = [10, '15', '20', 30]; $result = in_array(15, $user_ids); var_dump($result); // bool(true)Code language: HTML, XML (xml)

    To use the strict comparison, you pass false to the third argument ( $strict ) of the in_array() function as follows:

     $user_ids = [10, '15', '20', 30]; $result = in_array(15, $user_ids, true); var_dump($result); // bool(false)Code language: HTML, XML (xml)

    This time the in_array() function returns false instead.

    3) Using PHP in_array() function with the searched value is an array example

    The following example uses the in_array() function with the searched value is an array:

     $colors = [ ['red', 'green', 'blue'], ['cyan', 'magenta', 'yellow', 'black'], ['hue', 'saturation', 'lightness'] ]; if (in_array(['red', 'green', 'blue'], $colors)) < echo 'RGB colors found'; > else < echo 'RGB colors are not found'; >Code language: HTML, XML (xml)

    4) Using PHP in_array() function with an array of objects example

    The following defines the Role class that has two properties $id and $name :

     class Role < private $id; private $name; public function __construct($id, $name) < $this->id = $id; $this->name = $name; > >Code language: HTML, XML (xml)

    This example illustrates how to use the in_array() function to check if a Role object exists in an array of Role objects:

     // Role class $roles = [ new Role(1, 'admin'), new Role(2, 'editor'), new Role(3, 'subscribe'), ]; if (in_array(new Role(1, 'admin'), $roles)) < echo 'found it'; >Code language: HTML, XML (xml)

    If you set the $strict to true , the in_array() function will compare objects using their identities instead of values. For example:

    // Role class $roles = [ new Role(1, 'admin'), new Role(2, 'editor'), new Role(3, 'subscribe'), ]; if (in_array(new Role(1, 'admin'), $roles, true)) < echo 'found it!'; > else < echo 'not found!'; >Code language: PHP (php)

    Summary

    Источник

    Читайте также:  Php datetime to string with formatting
Оцените статью