PHP Search in Arrays Tutorial with Examples

Apr 20, 2021 . Admin

Hi Guys,

In this blog, I will show you how to probe in arrays utilizing PHP, We’ll ascertain 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.

Syntax:
array_search(val, arr, strict)

Parameters

  • val-The value to be searched
  • arr-The array to be searched
  • strict-Possible values are TRUE or FALSE. Search for identical elements in the array, set to TRUE.

Return

The array_search() function returns the key for val if it is found in the array. It returns FALSE if it is not found. If val is found in the array arr more than once, then the first matching key is returned.

Here i will give you full example for all array search function using php So let's see the bellow all example:

Example
<?php

  $myArr = ['science','maths','english','physics'];
  $search = array_search('english',$myArr);
  echo $search;

?>
Output
// output 
2
Syntax:
array_keys(array, value, strict);
Example : array_keys()

The array_keys() function returns an array containing the keys.

<?php

  $marks = [
    'science'=>80,
    'maths'=>70,
    'english'=>88,
    'physics'=>73,
    'chemistry'=>93
  ];
  $search = array_keys($marks,73);
  print_r($search);

?>
Output
Array
(
    [0] => physics
)
Syntax:
in_array(search, array, type);
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.

<?php

  $marks = [
    'science'=>80,
    'maths'=>70,
    'english'=>88,
    'physics'=>73,
    'chemistry'=>93
  ];

  if (in_array(93,$marks)) {
    echo("Found the value");
  } else {
    echo("Value doesn't exist");
  }

?>
Output
Found the value
Syntax:
array_key_exists(key, array)
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.

<?php

  $marks = [
    'science'=>80,
    'maths'=>70,
    'english'=>88,
    'physics'=>73,
    'chemistry'=>93
  ];

  
  if (array_key_exists("maths", $marks))
  {
      echo "Key exists in array!";
  }
  else
  {
      echo "Key doesn't exist in array!";
  }

?>
Output
Key exists in array!

It will help you..

#PHP