Summary: in this tutorial, you will learn how to lớn use the PHP in_array() function to kiểm tra if a value exists in an array.
Bạn đang xem: How to check if an array value exists?
The in_array() function returns true if a value exists in an array. Here’s the syntax of the in_array() function:
Code language: PHP (php)In this syntax:
The in_array() function searches for the $needle in the $haystack using the loose comparison (==). To lớn use the strict comparison (===), you need to lớn set the $strict argument to true.
If the value to check is a string, the in_array() function will tìm kiếm for it case-sensitively.
The in_array() function returns true if the $needle exists in the $array; otherwise, it returns false.
Let’s take some examples of using the in_array() function.
The following example uses the in_array() function to kiểm tra if the value "update" is in the $actions array:
$actions = <"new","edit","update","view","delete",>;$result = in_array("update", $actions);var_dump($result); // bool(true)
Code language: HTML, XML (xml)It returns true.
The following example returns false because the publish value doesn’t exist in the $actions array:
$actions = <"new","edit","update","view","delete",>;$result = in_array("publish", $actions);var_dump($result); // bool(false)
Code language: HTML, XML (xml)The following example returns false because the value "New" doesn’t exist in the $actions array. Lưu ý that the in_array() compares the strings case-sensitively:
$actions = <"new","edit","update","view","delete",>;$result = in_array("New", $actions);var_dump($result); // bool(false)
Code language: HTML, XML (xml)
$user_ids = <10, "15", "20", 30>;$result = in_array(15, $user_ids);var_dump($result); // bool(true)
Code language: HTML, XML (xml)To use the strict comparison, you pass false to lớn the third argument ($strict) of the in_array() function as follows:
$user_ids = <10, "15", "20", 30>;$result = in_array(15, $user_ids, true);var_dump($result); // bool(false)
Code language: HTML, XML (xml)This time the in_array() function returns false instead.
The following example uses the in_array() function with the searched value is an array:
$colors = <<"red", "green", "blue">,<"cyan", "magenta", "yellow", "black">,<"hue", "saturation", "lightness">>;if (in_array(<"red", "green", "blue">, $colors)) echo "RGB colors found"; else echo "RGB colors are not found";
Code language: HTML, XML (xml)Output:
RGB colors found
class Roleprivate $id;private $name;public function __construct($id, $name)$this->id = $id;$this->name = $name;
Code language: HTML, XML (xml)This example illustrates how to lớn use the in_array() function to kiểm tra if a Role object exists in an array of Role objects:
// Role class$roles =
Code language: HTML, XML (xml)Output:
found it!
If you phối the $strict to lớn true, the in_array() function will compare objects using their identities instead of values. For example:
// Role class$roles =
Code language: PHP (php)Output: