How to use if in array php

php in_array – Check If Value is in php Array

The php in_array() function allows us to check if a value is in a php array. The php in_array() function returns true if the value is in the array, and false if the value is not in the array.

From the php documentation, the php in_array() function takes 3 parameters:

in_array(mixed $needle, array $haystack, bool $strict = false): bool

In the syntax above, the needle is the value we want to check and the haystack is the array.

The third parameter strict is used if we want to use loose comparison (==) or strict comparison (===). Depending on how complex the structure of your array is, you will need to use the strict parameter to force strict comparison.

Using php in_array() To Check if String is in an Array of Strings

Let’s say we have the following array in php.

$sample_array = array("The", "polar", "bear", "is", "very", "big");

We can use the php in_array() function to check if the values “polar” and “express” are in the array. To do this, we call the php in_array() function in the following way, and echo the result.

$sample_array = array("The", "polar", "bear", "is", "very", "big"); // using json_encode because the php echo function prints "1" for true and "" for false echo json_encode(in_array("polar", $sample_array)); // true echo json_encode(in_array("express", $sample_array)); // false 

As expected, “polar” was found in the array, and “express” was not found in the array. When comparing strings, the php in_array() function is case sensitive. So, if we wanted to check if the value “Polar” was in the array, the function would return false. This is shown in the following example.

$sample_array = array("The", "polar", "bear", "is", "very", "big"); echo json_encode(in_array("Polar", $sample_array)); // false 

php in_array() Loose Comparison Example

In the example above, we used the php in_array() function to check if a string was in a list of strings. We didn’t need to use the strict parameter because both the needle and haystack values were the same type.

Читайте также:  Функция замены строки php

Let’s say we have the following array. This array has different types.

$sample_array = array("The", 2, "3", "three", "six", "Yankees", "sun");

Let’s see if a few different values are in this array with in_array() and see the effects of using loose comparison with in_array().

$sample_array = array("The", 2, "3", "three", "six", "Yankees", "sun"); echo json_encode(in_array("The", $sample_array)); // true echo json_encode(in_array("two", $sample_array)); // false echo json_encode(in_array(2, $sample_array)); // true echo json_encode(in_array(3, $sample_array)); // true echo json_encode(in_array("3", $sample_array)); // true 

What is interesting here is that when we check to see if the number 3 is in the array, the in_array() function returns true. This is because when we compare 3 and “3” using loose comparison, these are equal.

However, this is not the case with strict comparison.

php in_array() Strict Comparison Example

In the example above, we saw that when we use loose comparison in the php in_array() function, we can receive interesting results.

To use strict comparison, we pass true to the strict parameter in the in_array() function.

Let’s take the same array above and check the same values to see if they are in the array with strict comparison.

$sample_array = array("The", 2, "3", "three", "six", "Yankees", "sun"); echo json_encode(in_array("The", $sample_array, true)); // true echo json_encode(in_array("two", $sample_array, true)); // false echo json_encode(in_array(2, $sample_array, true)); // true echo json_encode(in_array(3, $sample_array, true)); // false echo json_encode(in_array("3", $sample_array, true)); // true 

In this example, we see that 3 is not equal to “3” with strict comparison, because 3 is an integer and “3” is a string.

Using in_array() to find an array in an array

We can also use the in_array() function to see if an array is inside another array.

Let’s say I have the following array of arrays in my php code:

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

We can use the in_array() function to check if the array [8,9,10] is in our array of arrays using the following code:

$sample_array_of_arrays = [ [0,1,2,3], [4,5,6,7], [8,9,10], ["0","1","2"] ]; echo json_encode(in_array([8,9,10], $sample_array_of_arrays)) // true 

As expected, the array [8,9,10] is in our array of arrays and the in_array() function returned true.

Can I use in_array() to find an object in an array?

The in_array() function is very useful in many cases. However, when looking to find if an object is in an array of objects, we need to be careful.

We can use loose comparison to find if an object has the same properties as another object in an array, but if we want to find out if an instance is the same, we need to use strict comparison.

Let’s say I have the following simple class:

class Person < private $id; private $name; private $age; public function __construct($id, $name, $age) < $this->id = $id; $this->name = $name; $this->age = $age; > > 

I can instantiate a few instances of this object, create an array, and check to see what’s in the array using our in_array() function below:

class Person < private $id; private $name; private $age; public function __construct($id, $name, $age) < $this->id = $id; $this->name = $name; $this->age = $age; > > $bob = new Person(1, 'Bob', 20); $sally = new Person(2, 'Sally', 35); $mike = new Person(3, 'Mike', 40); $patricia = new Person(4, 'Patricia', 15); $people = [ $bob, $sally, $mike, $patricia, ]; echo json_encode(in_array(new Person(4, 'Patricia', 15),$people)); // true echo json_encode(in_array(new Person(4, 'Patricia', 15), $people, true)); // false echo json_encode(in_array($patricia, $people, true)); // true 

As you can see, there is a difference here when using loose comparison and strict comparison – when using loose comparison, the in_array() function is checking only the values of each of the objects, where with strict comparison, the in_array() function is checking the if the instance is in the array.

Hopefully you now know how to use the php in_array() function to check if a value is in an array.

  • 1. php pi – Get Value of pi Using php pi() Function
  • 2. php asinh – Find Hyperbolic Arcsine of Number Using php asinh() Function
  • 3. php range() – Create Array of Elements Within Given Range
  • 4. php array_shift() – Remove the First Element from Array
  • 5. How to Add Items to Array in php
  • 6. Check if String Ends with Given String in php with str_ends_with()
  • 7. What is the Difference Between unset() and unlink() in php?
  • 8. How to Check If String Contains Substring in PHP
  • 9. php max – Find Maximum Value of Array in php
  • 10. php preg_match_all – Get All Matches of Pattern in String

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Источник

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

Источник

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