How to check an element is exists in array or not in PHP ?
An array may contain elements belonging to different data types, integer, character, or logical type. The values can then be inspected in the array using various in-built methods :
Approach 1 (Using in_array() method): The array() method can be used to declare an array. The in_array() method in PHP is used to check the presence of an element in the array. The method returns true or false depending on whether the element exists in the array or not.
PHP in_array Vs array_search
![]()
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!”;
>
?>
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 .
Возвращаемые значения
Возвращает 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» ;
>
?>