Как проверить наличие элемента в массиве php
Перейти к содержимому

Как проверить наличие элемента в массиве php

  • автор:

# Arrays

An array is a data structure that stores an arbitrary number of values in a single value. An array in PHP is actually an ordered map, where map is a type that associates values to keys.

# Initializing an Array

An array can be initialized empty:

An array can be initialized and preset with values:

An array can also be initialized with custom indexes (also called an associative array):

If the variable hasn’t been used before, PHP will create it automatically. While convenient, this might make the code harder to read:

The index will usually continue where you left off. PHP will try to use numeric strings as integers:

To initialize an array with fixed size you can use SplFixedArray

Note: An array created using SplFixedArray has a reduced memory footprint for large sets of data, but the keys must be integers.

To initialize an array with a dynamic size but with n non empty elements (e.g. a placeholder) you can use a loop as follows:

If all your placeholders are the same then you can also create it using the function array_fill()

This creates and returns an array with num entries of value , keys starting at start_index .

Note: If the start_index is negative it will start with the negative index and continue from 0 for the following elements.

(opens new window) you are more limited for what you can actually do. The loop is more flexible and opens you a wider range of opportunities.

Whenever you want an array filled with a range of numbers (e.g. 1-4) you could either append every single element to an array or use the range()

This function creates an array containing a range of elements. The first two parameters are required, where they set the start and end points of the (inclusive) range. The third parameter is optional and defines the size of the steps being taken. Creating a range from 0 to 4 with a stepsize of 1 , the resulting array would consist of the following elements: 0 , 1 , 2 , 3 , and 4 . If the step size is increased to 2 (i.e. range(0, 4, 2) ) then the resulting array would be: 0 , 2 , and 4 .

range can work with integers, floats, booleans (which become casted to integers), and strings. Caution should be taken, however, when using floats as arguments due to the floating point precision problem.

# Check if key exists

Note that isset() treats a null valued element as non-existent. Whereas !empty() does the same for any element that equals false (using a weak comparision; for example, null , » and 0 are all treated as false by !empty() ). While isset($map[‘foobar’]); is true , !empty($map[‘foobar’]) is false . This can lead to mistakes (for example, it is easy to forget that the string ‘0’ is treated as false) so use of !empty() is often frowned upon.

Note also that isset() and !empty() will work (and return false) if $map is not defined at all. This makes them somewhat error-prone to use:

You can also check for ordinal arrays:

Note that isset() has better performance than array_key_exists() as the latter is a function and the former a language construct.

You can also use key_exists()

(opens new window) , which is an alias for array_key_exists() .

# Validating the array type

(opens new window) returns true if a variable is an array.

You can type hint the array type in a function to enforce a parameter type; passing anything else will result in a fatal error.

You can also use the gettype()

# Creating an array of variables

This method is often used in frameworks to pass an array of variables between two components.

# Checking if a value exists in array

(opens new window) returns true if an item exists in an array.

You can also use the function array_search()

(opens new window) to get the key of a specific item in an array.

In PHP 5.5 and later you can use array_column()

(opens new window) in conjunction with array_search() .

# ArrayAccess and Iterator Interfaces

Another useful feature is accessing your custom object collections as arrays in PHP. There are two interfaces available in PHP (>=5.0.0) core to support this: ArrayAccess and Iterator . The former allows you to access your custom objects as array.

ArrayAccess

Assume we have a user class and a database table storing all the users. We would like to create a UserCollection class that will:

  1. allow us to address certain user by their username unique identifier
  2. perform basic (not all CRUD, but at least Create, Retrieve and Delete) operations on our users collection

Consider the following source (hereinafter we’re using short array creation syntax [] available since version 5.4):

which will output the following, assuming there was no testuser before we launched the code:

IMPORTANT: offsetExists is not called when you check existence of a key with array_key_exists function. So the following code will output false twice:

Iterator

Let’s extend our class from above with a few functions from Iterator interface to allow iterating over it with foreach and while .

First, we need to add a property holding our current index of iterator, let’s add it to the class properties as $_position :

Second, let’s add Iterator interface to the list of interfaces being implemented by our class:

then add the required by the interface functions themselves:

So all in all here is complete source of the class implementing both interfaces. Note that this example is not perfect, because the IDs in the database may not be sequential, but this was written just to give you the main idea: you can address your objects collections in any possible way by implementing ArrayAccess and Iterator interfaces:

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:

  • $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:

It returns true .

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

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:

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 ( == ):

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

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:

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 :

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

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

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()

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

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

<?php
$a = array( ‘1.10’ , 12.4 , 1.13 );

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

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

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

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

<?php
$a = array(array( ‘p’ , ‘h’ ), array( ‘p’ , ‘r’ ), ‘o’ );

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.

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:

<?php
// .
$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.

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

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.

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

PHP in_array Vs array_search

Alam Riku

Assalamualaikum , I am going to explain the difference between mostly used PHP built-in function. What I faced when implementing these function on a particular web application.

in_array

in_array — Checks if a value exists in an array

in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : bool

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

needle : The searched value.If needle is a string, the comparison is done in a case-sensitive manner.

haystack: The array.

strict: 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 .

Return Values : Returns TRUE if needle is found in the array, FALSE otherwise.

<?php
$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:

array_search()

array_search — Searches the array for a given value and returns the first corresponding key if successful

array_search ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : mixed

Searches for needle in haystack .

Return Value: Returns the key for needle if it is found in the array, FALSE otherwise.

<?php
$arr = array(“nice”,”car”,”none”);
var_dump(array_search(“car”, ($arr)));

This function may return Boolean FALSE , but may also return a non-Boolean value which evaluates to FALSE . Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

non-Boolean value which evaluates to FALSE

$array = [“a”,”b”,”c”,”d”];
$key = array_search(“a”, $array); //$key = 0
if ($key)
<
//even a element is found in array, but if (0) means false
//…
>
//the correct way
if (false !== $key)
<
echo $key;
>

$key = array_search(‘a’, $array)

array_search return key if found else return false

array_search: If needle is found in haystack more than once, the first matching key is returned.

in_array return true if found else return false

If you’re working with very large 2 dimensional arrays (eg 20,000+ elements) it’s much faster to do this…

<?php
$needle = ‘test for this’;

if ( isset($flipped_haystack[$needle]) )
<
print “Yes it’s there!”;
>
?>

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *