PHP: Search array for substring.

This is a guide on how to use PHP to search for a particular substring in an array. In this tutorial, we will create a custom function that loops through an array and checks each element for a given substring.

Let’s take a look at the following PHP snippet:

<?php

//We create an array called $animals.
$animals = array(
    'Dog',
    'Cat',
    'Zebra',
    'Lion',
    'Elephant'
);

//Our custom function.
function stristrarray($array, $str){
    //This array will hold the indexes of every
    //element that contains our substring.
    $indexes = array();
    foreach($array as $k => $v){
        //If stristr, add the index to our
        //$indexes array.
        if(stristr($v, $str)){
            $indexes[] = $k;
        }
    }
    return $indexes;
}

//Searching for the substring "cat" will return one result.
$result = stristrarray($animals, 'cat');
//The result is an array containing "1"
var_dump($result);

Inside our function:

  1. We create an empty array called $indexes. This will be filled with the indexes of any elements that contain our given substring.
  2. We loop through every element in the array.
  3. Inside our loop, we check to see if the given substring is present.
  4. If it is present, we add the index of that element to our $indexes array.
  5. Finally, we return the $indexes array.

If the substring is not found, our custom function will return an empty array. If the string is found in multiple elements, then the returned array will contain multiple elements.