How to check an element is exists in array or not in PHP ?
An array may contain elements belonging to different data types, integer, character, or logical type. The values can then be inspected in the array using various in-built methods :
Approach 1 (Using in_array() method): The array() method can be used to declare an array. The in_array() method in PHP is used to check the presence of an element in the array. The method returns true or false depending on whether the element exists in the array or not.
in_array(element , array)
- element: The element to check in the array
- array: The array to look for element
Original Array: ["Hello","GEEKs","User","PHP"] GEEKs - Element found.
Approach 2 (Using for loop): A for loop iteration is done throughout the array. A boolean flag is declared to check for the presence of an element. It is initialized to the boolean value of false. In case the value is false, and the element is found in the array, the flag value is changed to the true value. No further modifications in the flag value are made.
Original Array [1, 3, 5, 6] 5 - Element found.