PHP Search in Arrays Tutorial with Examples
Teams applying “PHP Search in Arrays Tutorial with Examples” in a production project can use the corresponding workflow to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.
Before copying the example into a live application, confirm version-specific behaviour with the PHP project and test it against the project’s actual database and runtime.
Hello Friends,
In this blog, I will show you how to search in arrays using PHP, We’ll find out how to search through the arrays in PHP. Working with arrays in php is made simple by its some standard built-in functions like array_search, array_key_exists, keys, and in_array.
Here i will give you full example for all array search function using php So let's see the bellow all example:
Example : array_search()
PHP array_search() is an inbuilt function that searches an array for a value and returns the key. The array_search() function returns the key for value if it is found in the array.
$myArray = ['car', 'bike', 'bus', 'truck'];
$search = array_search('bike', $myArray);
echo $search;
// Output - int(1)
Output
int(1)
Example : array_keys()
The array_keys() function returns an array containing the keys.
$myArray = [
'car' => 'bmw',
'bike' => 'ktm',
'bus' => 'volvo',
'truck' => 'ashok layland'
];
$search = array_keys($myArray, 'volvo');
print_r($search);
// Output - Array ( [0] => bus )
Output
Array ( [0] => bus )
Example : in_array()
The in_array() function searches an array for a specific value. Returns true if needle is found in the array, false otherwise.
$myArray = [
'car' => 'bmw',
'bike' => 'ktm',
'bus' => 'volvo',
'truck' => 'ashok layland'
];
if (in_array("volvo", $myArray))
{
echo "Found the value";
}
else
{
echo "Value doesn't exist";
}
// Output - Found the value
Output
Found the value
Example : array_key_exists()
The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.
$myArray = [
'car' => 'bmw',
'bike' => 'ktm',
'bus' => 'volvo',
'truck' => 'ashok layland'
];
if (array_key_exists("bus", $myArray))
{
echo "Key exists in array!";
}
else
{
echo "Key doesn't exist in array!";
}
// Output - Key exists in array!
Output
Key exists in array!
It will help you....
- How To Use Php Conditional Statement Example
- How to Check if String Contains Regex in PHP?
- PHP Array_column() Function Example
- PHP Generate List of Random Numbers Between 0 and 100 Example
- How to User Login with Facebook in PHP?
- How to Explode Every Character into Array Using PHP Example?
- PHP Form Validation Tutorial
- PHP Convert XML to JSON Example