The PHP in_array() function allows you to check for the presence of a value in an array, and take an option based on this result.
Syntax
in_array ( $needle , $haystack [, $strict = FALSE ] )
Note That:
- $needle can be a variable of any type (string, number, date, etc)
- $haystack should be an array (see here, here, and here for more about arrays)
- $strict is optional, and will ensure that the type of values is also compared when checking whether $needle is present
- If $strict is FALSE (the default behavior), the number 1 and the string “1” will be considered the same when comparing values to check whether the value appears in $haystack
- A boolean value is returned (TRUE/FALSE), allowing you to take an action based on whether the $needle value was present in the $haystack array – see more about comparing boolean values here
Examples
As an example, we can check whether a value is present in an array containing the days of the working week:
$weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]; $result = in_array("Saturday", $weekdays); // FALSE if($result == FALSE) { echo "Saturday is not a weekday."; }
Strict
The $strict option is not required but can be useful, especially when dealing with user input. By default in_array() will treat values of different types but the same content as being a match – 12 (a number/integer) and “12” (a string which happens to contain characters representing a number) would be treated as being a match.
Strict mode will prevent this, meaning that 12 (a number) “12” (a string which happens to contain characters representing a number) are treated as not matching due to being of different types:
$numbers = [3, 7, 11, 12]; $result = in_array("12", $numbers); // TRUE $result = in_array("12", $numbers, TRUE); // FALSE
- The result of the first in_array() check returns TRUE as it is not being strict about the variable type
- The result of the second in_array() check returns FALSE as the types are different – the $needle is a string, but the value in the $haystack is a number, as it is not wrapped in quotes
Conclusion
Determining whether a value is present in an array can be used to do things like checking if the user has submitted a correct answer for a quiz, checking if the date of a reservation is already taken, or seeing if a user has already entered a value in a form. It’s a useful function when making sure the data is clean and well-formatted.
Click here for more PHP tutorials from LinuxScrew!
To view the official documentation for the PHP in_array() function: