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

How can I check if an array element exists?

Of course, the first time I want an instance, $instances will not know the key. I guess my check for available instance is wrong?

8 Answers 8

You can use either the language construct isset , or the function array_key_exists .

isset should be a bit faster (as it’s not a function), but will return false if the element exists and has the value NULL .

For example, considering this array :

$a = array( 123 => 'glop', 456 => null, ); 

And those three tests, relying on isset :

var_dump(isset($a[123])); var_dump(isset($a[456])); var_dump(isset($a[789])); 

The first one will get you (the element exists, and is not null) :

While the second one will get you (the element exists, but is null) :

And the last one will get you (the element doesn’t exist) :

On the other hand, using array_key_exists like this :

var_dump(array_key_exists(123, $a)); var_dump(array_key_exists(456, $a)); var_dump(array_key_exists(789, $a)); 
boolean true boolean true boolean false 

Because, in the two first cases, the element exists — even if it’s null in the second case. And, of course, in the third case, it doesn’t exist.

For situations such as yours, I generally use isset , considering I’m never in the second case. But choosing which one to use is now up to you 😉

For instance, your code could become something like this :

if (!isset(self::$instances[$instanceKey]))

I have to complain ’cause isset is typo-unsafe. Called $form = [1 => 5]; var_dump(isset($from[1])); returns false since $from does not exist and you aren’t even notified by E_NOTICE . Slower, but safer array_key_exists do the thing for me.

array_key_exists() is SLOW compared to isset(). A combination of these two (see below code) would help.

It takes the performance advantage of isset() while maintaining the correct checking result (i.e. return TRUE even when the array element is NULL)

if (isset($a['element']) || array_key_exists('element', $a)) < //the element exists in the array. write your code here. >

The benchmarking comparison: (extracted from below blog posts).

array_key_exists() only : 205 ms isset() only : 35ms isset() || array_key_exists() : 48ms 

And, isset is also misleading. Why would a keyword named «is set» return false when a variable, or an array position, is actually set — even though it is set to null?

You can use the function array_key_exists to do that.

$a=array("a"=>"Dog","b"=>"Cat"); if (array_key_exists("a",$a)) < echo "Key exists!"; >else

You can use isset() for this very thing.

$myArr = array("Name" => "Jonathan"); print (isset($myArr["Name"])) ? "Exists" : "Doesn't Exist" ; 

According to the PHP manual you can do this in two ways. It depends what you need to check.

If you want to check if the given key or index exists in the array use array_key_exists

 1, 'second' => 4); if (array_key_exists('first', $search_array)) < echo "The 'first' element is in the array"; >?> 

If you want to check if a value exists in an array use in_array

Читайте также:  Image with name in html

You want to use the array_key_exists function.

A little anecdote to illustrate the use of array_key_exists .

// A programmer walked through the parking lot in search of his car // When he neared it, he reached for his pocket to grab his array of keys $keyChain = array( 'office-door' => unlockOffice(), 'home-key' => unlockSmallApartment(), 'wifes-mercedes' => unusedKeyAfterDivorce(), 'safety-deposit-box' => uselessKeyForEmptyBox(), 'rusto-old-car' => unlockOldBarrel(), ); // He tried and tried but couldn't find the right key for his car // And so he wondered if he had the right key with him. // To determine this he used array_key_exists if (array_key_exists('rusty-old-car', $keyChain))

Источник

in_array

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

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

Замечание:

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

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

Замечание:

До PHP 8.0.0 строковое значение параметра needle будет соответствовать значению массива 0 в нестрогом режиме, и наоборот. Это может привести к нежелательным результатам. Подобные крайние случаи существуют и для других типов. Если нет полной уверенности в типах значений, всегда используйте флаг strict , чтобы избежать неожиданного поведения.

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

Возвращает 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() — Проверяет, присутствует ли в массиве указанный ключ или индекс

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.

Читайте также:  Html and css table template

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 ],
];

Читайте также:  Replace all in arraylist java

$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!’ );

Источник

How to check if an array value exists?

Is it possible to have an array with identical keys? Wouldn’t the second value overwrite the original?

if(isset($something['say']) && $something['say'] === 'bla') < // do something >

By the way, you are assigning a value with the key say twice, hence your array will result in an array with only one value.

Using: in_array()

$search_array = array('user_from','lucky_draw_id','prize_id'); if (in_array('prize_id', $search_array))

Here is output: The ‘prize_id’ element is in the array

Using: array_key_exists()

$search_array = array('user_from','lucky_draw_id','prize_id'); if (array_key_exists('prize_id', $search_array))

In conclusion, array_key_exists() does not work with a simple array. Its only to find whether an array key exist or not. Use in_array() instead.

Here is more example:

 'bla', 'b' => 'omg'); if (in_array('omg', $something)) < echo "|1| The 'omg' value found in the assoc array ||"; >/**++++++++++++++++++++++++++++++++++++++++++++++ * 2. example with index array using in_array * * IMPORTANT NOTE: in_array is case-sensitive * in_array — Checks if a value exists in an array * * DOES NOT WORK FOR MULTI-DIMENSIONAL ARRAY *++++++++++++++++++++++++++++++++++++++++++++++ */ $something = array('bla', 'omg'); if (in_array('omg', $something)) < echo "|2| The 'omg' value found in the index array ||"; >/**++++++++++++++++++++++++++++++++++++++++++++++ * 3. trying with array_search * * array_search — Searches the array for a given value * and returns the corresponding key if successful * * DOES NOT WORK FOR MULTI-DIMENSIONAL ARRAY *++++++++++++++++++++++++++++++++++++++++++++++ */ $something = array('a' => 'bla', 'b' => 'omg'); if (array_search('bla', $something)) < echo "|3| The 'bla' value found in the assoc array ||"; >/**++++++++++++++++++++++++++++++++++++++++++++++ * 4. trying with isset (fastest ever) * * isset — Determine if a variable is set and * is not NULL *++++++++++++++++++++++++++++++++++++++++++++++ */ $something = array('a' => 'bla', 'b' => 'omg'); if($something['a']=='bla') < echo "|4| Yeah!! 'bla' found in array ||"; >/** * OUTPUT: * |1| The 'omg' element value found in the assoc array || * |2| The 'omg' element value found in the index array || * |3| The 'bla' element value found in the assoc array || * |4| Yeah!! 'bla' found in array || */ ?> 

Источник

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