Проверить существует ли массив 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

    Searches for needle in haystack using loose comparison unless strict is set.

    Parameters

    Note:

    If needle is a string, the comparison is done in a case-sensitive manner.

    If the third parameter strict is set to true then the in_array() function will also check the types of the needle in the haystack .

    Note:

    Prior to PHP 8.0.0, a string needle will match an array value of 0 in non-strict mode, and vice versa. That may lead to undesireable results. Similar edge cases exist for other types, as well. If not absolutely certain of the types of values involved, always use the strict flag to avoid unexpected behavior.

    Return Values

    Returns true if needle is found in the array, false otherwise.

    Examples

    Example #1 in_array() example

    $os = array( «Mac» , «NT» , «Irix» , «Linux» );
    if ( in_array ( «Irix» , $os )) echo «Got Irix» ;
    >
    if ( in_array ( «mac» , $os )) echo «Got mac» ;
    >
    ?>

    The second condition fails because in_array() is case-sensitive, so the program above will display:

    Example #2 in_array() with strict example

    if ( in_array ( ‘12.4’ , $a , true )) echo «‘12.4’ found with strict check\n» ;
    >

    if ( in_array ( 1.13 , $a , true )) echo «1.13 found with strict check\n» ;
    >
    ?>

    The above example will output:

    1.13 found with strict check

    Example #3 in_array() with an array as needle

    if ( in_array (array( ‘p’ , ‘h’ ), $a )) echo «‘ph’ was found\n» ;
    >

    if ( in_array (array( ‘f’ , ‘i’ ), $a )) echo «‘fi’ was found\n» ;
    >

    if ( in_array ( ‘o’ , $a )) echo «‘o’ was found\n» ;
    >
    ?>

    The above example will output:

    See Also

    • array_search() — Searches the array for a given value and returns the first corresponding key if successful
    • isset() — Determine if a variable is declared and is different than null
    • array_key_exists() — Checks if the given key or index exists in the array

    User Contributed Notes 8 notes

    Loose checking returns some crazy, counter-intuitive results when used with certain arrays. It is completely correct behaviour, due to PHP’s leniency on variable types, but in «real-life» is almost useless.

    The solution is to use the strict checking option.

    $array = array(
    ‘egg’ => true ,
    ‘cheese’ => false ,
    ‘hair’ => 765 ,
    ‘goblins’ => null ,
    ‘ogres’ => ‘no ogres allowed in this array’
    );

    // Loose checking — return values are in comments

    // First three make sense, last four do not

    in_array ( null , $array ); // true
    in_array ( false , $array ); // true
    in_array ( 765 , $array ); // true
    in_array ( 763 , $array ); // true
    in_array ( ‘egg’ , $array ); // true
    in_array ( ‘hhh’ , $array ); // true
    in_array (array(), $array ); // true

    in_array ( null , $array , true ); // true
    in_array ( false , $array , true ); // true
    in_array ( 765 , $array , true ); // true
    in_array ( 763 , $array , true ); // false
    in_array ( ‘egg’ , $array , true ); // false
    in_array ( ‘hhh’ , $array , true ); // false
    in_array (array(), $array , true ); // false

    I got an unexpected behavior working with in_array. I’m using following code:

    // .
    $someId = getSomeId (); // it gets generated/fetched by another service, so I don’t know what value it will have. P.S.: it’s an integer

    // The actual data in my edge-case scenario:
    // $someId = 0;
    // $anyArray = [‘dataOne’, ‘dataTwo’];
    if ( in_array ( $someId , $anyArray )) // do some work
    >
    // .
    ?>

    With PHP7.4, in_array returns boolean true.
    With PHP8.1, in_array returns boolean false.

    It took me quite some time to find out what’s going on.

    I found out that in_array will *not* find an associative array within a haystack of associative arrays in strict mode if the keys were not generated in the *same order*:

    $needle = array(
    ‘fruit’ => ‘banana’ , ‘vegetable’ => ‘carrot’
    );

    $haystack = array(
    array( ‘vegetable’ => ‘carrot’ , ‘fruit’ => ‘banana’ ),
    array( ‘fruit’ => ‘apple’ , ‘vegetable’ => ‘celery’ )
    );

    echo in_array ( $needle , $haystack , true ) ? ‘true’ : ‘false’ ;
    // Output is ‘false’

    echo in_array ( $needle , $haystack ) ? ‘true’ : ‘false’ ;
    // Output is ‘true’

    ?>

    I had wrongly assumed the order of the items in an associative array were irrelevant, regardless of whether ‘strict’ is TRUE or FALSE: The order is irrelevant *only* if not in strict mode.

    I’d like to point out that, if you’re using Enum data structures and want to compare whether an array of strings has a certain string Enum in it, you need to cast it to a string.

    From what I’ve tested, the function works correctly:
    if the array is filled with strings and you’re searching for a string;
    if the array is filled with Enums and you’re searching for an Enum.

    Here is a recursive in_array function:

    $myNumbers = [
    [ 1 , 2 , 3 , 4 , 5 ],
    [ 6 , 7 , 8 , 9 , 10 ],
    ];

    $array = [
    ‘numbers’ => $myNumbers
    ];

    // Let’s try to find number 7 within $array
    $hasNumber = in_array ( 7 , $array , true ); // bool(false)
    $hasNumber = in_array_recursive ( 7 , $array , true ); // bool(true)

    function in_array_recursive ( mixed $needle , array $haystack , bool $strict ): bool
    foreach ( $haystack as $element ) if ( $element === $needle ) return true ;
    >

    $isFound = false ;
    if ( is_array ( $element )) $isFound = in_array_recursive ( $needle , $element , $strict );
    >

    if ( $isFound === true ) return true ;
    >
    >

    If you’re creating an array yourself and then using in_array to search it, consider setting the keys of the array and using isset instead since it’s much faster.

    $slow = array( ‘apple’ , ‘banana’ , ‘orange’ );

    if ( in_array ( ‘banana’ , $slow ))
    print( ‘Found it!’ );

    $fast = array( ‘apple’ => ‘apple’ , ‘banana’ => ‘banana’ , ‘orange’ => ‘orange’ );

    if (isset( $fast [ ‘banana’ ]))
    print( ‘Found it!’ );

    Источник

    is_array

    Возвращает true если value является массивом, иначе — false .

    Examples

    Пример # 1 Убедитесь, что переменная является массивом

     $yes = array('this', 'is', 'an array'); echo is_array($yes) ? 'Array' : 'not an Array'; echo "\n"; $no = 'this is a string'; echo is_array($no) ? 'Array' : 'not an Array'; ?>

    Выводится приведенный выше пример:

    See Also

    • is_float () — Проверяет , является ли тип переменной float
    • is_int () — определяет, является ли тип переменной целым числом
    • is_string () — Узнает , является ли переменная строковым
    • is_object () — Проверяет , является ли переменная объектом
    PHP 8.2

    (PHP 4 4.2.0,5,7,8)is_a Проверяет,является ли объект данного класса или имеет одного из его родителей Проверяет,является ли данный объект_или_класс данным и имеет ли одного из его родителей.

    (PHP 4,5,7,8)is_bool Выясняет,является ли переменная булевой Выясняет,является ли данная переменная булевой.

    (PHP 4 4.0.6,5,7,8)is_callable Убедитесь,что значение может быть вызвано как функция из текущей области видимости.

    Источник

    Проверка на существование и пустоту в PHP

    Часто возникают ситуации, когда нужно проверить существование или пустоту переменной. В PHP для этого есть функции isset() , empty() и array_key_exists() .

    Проверка существования переменной

    Функция isset() возвращает true , если переменная существует и её значение не null :

    Если передать в isset несколько переменных, она вернёт true при существовании всех переменных:

    '; echo isset($name, $age, $status) ? 'Василиса есть' : 'Василисы нет';
    Василиса есть Василисы нет

    Операторы объединения с NULL

    В PHP 7 появился оператор объединения с NULL (или NULL-коалесцентный оператор) ?? . Он позволяет получить значение переменной, если она задана и не равна NULL, а иначе — значение по-умолчанию:

    В PHP 7.4 появился присваивающий оператор объединения с NULL ??= .Он позволяет удобно задать значение переменной, если эта переменная ещё не задана (либо равна NULL):

    // Как было раньше $name = $name ?? 'Василий'; // Как стало в PHP 7.4 $name ??= 'Василий';

    Проверка на пустоту

    Напомню, переменная считается пустой (приводится к false), если она имеет одно из следующих значений:

    • 0 (целое или дробное)
    • » (пустая строка)
    • ‘0’ (строка с числом 0)
    • [] (пустой массив)
    • null

    Функция empty() возвращает true , если переменная не существует или пустая:

    Поведение isset() и empty() сначала может немного запутать: первая возвращает true при существовании переменной, вторая — при не существовании. К этому нужно просто привыкнуть.

    На самом деле isset() и empty() , аналогично echo , являются синтаксическими конструкциями, а не функциями.

    Функции isset() и empty() гасят ошибку обращения к несуществующей переменной. Это одна из причин, почему они не являются обычными функциями.

    ceil($var); // Notice: Undefined variable: var isset($var); // Ошибки нет

    Существование элемента массива

    Как мы узнали чуть выше, isset() возвращает false , если переменная существует, но имеет значение null .

    Бывают ситуации, когда нам необходимо точно знать, существует ли определённый элемент массива или нет, даже если его значение NULL.

    Для этого в PHP существует функция array_key_exists() :

    Источник

    Читайте также:  Python dataframe str replace
Оцените статью