What is the use of in_array() function in PHP?

in_array() checks if a value exists in an array. It returns true if the value is found, and false if not.

<?php
$fruits = ["Apple", "Banana", "Cherry"];

var_dump(in_array("Banana", $fruits));
var_dump(in_array("Mango", $fruits));

// Third parameter true = check the data type also
var_dump(in_array("1", [1, 2, 3]));
var_dump(in_array("1", [1, 2, 3], true));
?>

Output:

Tutorials Class - Output Window

bool(true)
bool(false)
bool(true)
bool(false)

By default in_array() compares loosely, so the string “1” matches the number 1. Pass true as the third parameter for a strict comparison. To get the position of the value, use array_search(), and to check a key use array_key_exists().


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.