![]() |
Given an array and an item, the task is to search whether the given item is present in the array or not. Below are the approaches to search an item in an array in PHP: Table of Content Using in_array() FunctionThe in_array() function checks if a value exists in an array. It returns true if the value is found, and false otherwise. Example: The in_array() function is very basic and checks if the value 30 exists in the array.
Output 30 exist in array. Using array_search() FunctionThe array_search() function searches for a value in an array and returns the key if found. If the value is not found, it returns false. Example: The example shows the use of array_search() function.
Output 30 exist in array. Using array_key_exists() FunctionIf you want to search for a key in an associative array, array_key_exists() is the right function to use. It checks if the given key or index exists in the array. The array_key_exists() function checks if the key “C” exists in the associative array. Example: This example shows the use of array-key_exists() function for searching an item in an array.
Output C exist in array. Using a LoopIf you need to perform a more complex search, you can use a loop to iterate through the array and check each element. The loop iterates through the array and compares each element with the search value 30. If a match is found, it prints the index and breaks the loop. Example: This example shows the use of loop for searching an element in an array.
Output 30 Exist in Array at Index 2. Using array_filter() with count()In this approach we use array_filter() to create a new array containing elements that match the search value and then checks if the filtered array has any elements using count(). If the count is greater than zero, the item exists in the original array. Example: This example shows the use of array_filter() with count() method to search an element in an array.
Output banana found in the array. |
Reffered: https://www.geeksforgeeks.org
PHP |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 18 |