What is the in_array method in PHP?
The in_array method checks if a value is present in an array.
Syntax
in_array(mixed $value, array $haystack, bool $strict = false): bool
Parameters
-
value: The value to be searched for in an array. -
haystack: The array that will be searched. -
strict: An optional boolean argument. If we passtrueas the value, then thein_arrayfunction will also check the types of thevalue. By default, the value of thestrictargument isfalse.
Return value
The function returns true if value is in the haystack. Otherwise, false is returned.
Code
Example 1
<?php$learning_platform = array("Udemy", "Udacity", "Educative");if (in_array("Educative", $learning_platform)) {echo "Educative is present";}if (in_array("Facebook", $learning_platform)) {echo "Facebook is present";}?>
Explanation
In the code above, we create an array with the name learning_platform.
-
We first use the
in_arraymethod to check if theEducativestring is present in the created array. Thein_arraymethod will returntruebecauseEducativeis present in the array. -
We then check if the
Facebookstring is present in the created array. Thein_arraymethod will returnfalsebecauseFacebookis not present in the array.
Example 2
<?php$num = array(1,2);if (in_array("1", $num)) {echo "1 is present\n";}if (in_array("1", $num, true)) {echo "1 is present";} else {echo "1 is not present";}?>
Explanation
In the code above, we create an array with the name num and the values 1 and 2.
$num = array(1,2)
We first check if 1 is present in the array.
in_array("1", $num)
By default, the type of the value to be searched is not checked, so the in_array method will return true.
We then use the in_array method to check if 1 is present in the array. To do this, we set the value as true for the strict argument.
in_array("1", $num, true)
In this case, the type of the value to be searched is also checked, so the in_array method will return false.