PHP find value in an arrayWhile working with a PHP array, the programmer often needs to search for a value while importing the data from the database. To ease the workload, PHP developers have already introduced few inbuilt functions that help the user search and locate a specific value in the given array. Below provided are the two PHP functions used to search values in an array:
This tutorial will briefly cover the syntax, return value, parameters, and various examples of both functions. 1. PHP array_search() functionThe PHP array_search() is an inbuilt function that is widely used to search and locate a specific value in the given array. If it successfully finds the specific value, it returns its corresponding key value. If the element is found twice or more, then the first occurrence of the matching value's key will be returned. Syntax Parameters The array_search() function takes three parameters, out of which two parameters are mandatory, and the last one is optional. The parameters of this function are as follows:
Return The array_search() function returns the corresponding element's key that is passed.
Example 1: In the below program, we learn how to search for an array value with the help of array_search() function where the strict_parameter is set to its default value . Output Dilip is at position 1 Example 2: In the below program, we learn how to search for an array value with the help of array_search() function if the strict_parameter is set to FALSE. Output 100 is at position 5 Example 3: In the below program, we learn how to search for an array value with the help of array_search() function if the strict_parameter is set to TRUE. Output 100 is at position 2. PHP in_array() FunctionThe PHP in_array() function is also an inbuilt function that is used to find whether the specified element is present in the given array or not. This function returns a Boolean value TRUE if the given value exists in an array, else it returns FALSE if the value is not found. Syntax Parameters The in_array() function takes the following three parameters, out of which two are mandatory and the remaining one is optional:
Returns The in_array() function returns a Boolean value i.e., either TRUE or False. It returns a boolean True if the search value is found in the given array. Else it returns FALSE if the value is not found. Example 1: In the below program, we have implemented the in_array() function to perform the array search operation in a non-strict mode. For this, we have set the last parameter $mode to false, which is its default value. Output The element 10 exits in the array. Example 2: In the below program, we have implemented the in_array() function to perform the array search operation in a strict mode. For this, we have set the last parameter $mode to True. Output The element '23' does not exist in the array. The element 'Indranil' does not exists in the array. The element 'Reema' does not exists in the array. |