in_array() and array_search()
Learn to check element existence with in_array() and find position with array_search().
Existence check with in_array()
in_array() checks whether an element exists in an array. in_array("Ali", $names) returns true if "Ali" is in $names, otherwise false.
By default it does type juggling; in_array("1", [1, 2]) returns true because PHP treats "1" and 1 as equal. For a strict comparison that also checks the type, pass true as the third argument: in_array("1", [1, 2], true) now returns false.
Finding position with array_search()
array_search() returns the key (index) of an element in the array. array_search("Ali", $names) gives the index of "Ali"; if not found, it returns false.
While in_array only tells you if it exists, array_search also gives the position. The third argument true enables strict comparison. When checking the result, use ===, because index 0 can be confused with 'not found'.
Exercise Search and print the index
Define $names = ["Alex", "Maya", "Sam"]. Get the index of "Maya" with $pos = array_search("Maya", $names). Then print it with echo $pos . "\n".
Show example solution
Get the index with $pos = array_search("Maya", $names);. Then print echo $pos . "\n";.
Example solution:
<?php
$names = ["Alex", "Maya", "Sam"];
// Find Maya's index and print it
$pos = array_search("Maya", $names);
echo $pos . "\n";
Test yourself
-
What does in_array return?
- The index
- The element itself
- A new array
- true/false
Show answer
true/false — Correct. in_array returns true if found, false otherwise.
-
Check if Ali is in the array
$names = ["Ali", "Ayşe", "Mehmet"]; if (____("Ali", $names)) { echo "Found"; }Show answer
$names = ["Ali", "Ayşe", "Mehmet"]; if (in_array("Ali", $names)) { echo "Found"; } -
Match each function to its return
- in_array
- true or false
- array_search
- Index or false
- array_pop
- Removed element
-
What does array_search("Ayşe", ["Ali", "Ayşe", "Mehmet"]) return?
- 0
- 1
- true
- Ayşe
Show answer
1 — Correct. Ayşe is at index 1; array_search returns 1.