Expand To Show Full Article
PHP in_array(): Check if Array Contains Value (5 Code Examples)
Skip to content
Home » PHP in_array(): Check if Array Contains Value (5 Code Examples)

PHP in_array(): Check if Array Contains Value (5 Code Examples)

How to Use PHP in_array function to check if the array contains a value

Arrays are an important data structure in PHP, allowing developers to store and manipulate a collection of values. Often, developers need to check if an array contains a specific value. One way to accomplish this in PHP is using the in_array() function. This function returns a boolean value indicating whether a specified value exists in an array. 

This article will discuss the syntax and usage of the in_array() function with examples.

PHP in_array Code Example

<?php

/*
Recursive approach
*/

$students = array(
  array("name" => "John", "age" => 20, "courses" => array("Math", "Science")),
  array("name" => "Mary", "age" => 22, "courses" => array("History", "English")),
  array("name" => "Peter", "age" => 24, "courses" => array("Computer Science", "Physics"))
);

function searchArray($needle, $haystack) {
  foreach($haystack as $value) {
    //If array within array
    if(is_array($value)) {
      //Recursively call the function on the array.
      if(searchArray($needle, $value)) {
        return true;
      }
    } else {
      if(in_array($needle, $haystack)) {
        return true;
      }
    }
  }
  return false;
}

$search_course = "Physics";

foreach ($students as $student) {
  //Search if a student is enrolled in Physics.
  if (searchArray($search_course, $student)) {
    echo "Course found for " . $student['name'];
  } else {
    echo "Course not found for " . $student['name'];
  }
}

/*
OUTPUT
Course not found for John
Course not found for Mary
Course found for Peter
*/


?>

Article Highlights

  • The in_array() function in PHP can be used to search for a specific value within an array.
  • The function’s syntax includes the $needle parameter (the value to search for), the $haystack parameter (the array to search in), and an optional $strict parameter for performing strict type comparisons.
  • Basic usage of in_array() involves passing a value to search for, an array to search in, and an optional strict comparison flag.
  • Check a value in a multi-dimensional using either the iterative approach or the recursive approach.
  • The iterative approach has limitations, including performance hits and increased code complexity.
  • The recursive approach performs more on large, more complex data structures.

Table of Contents

Syntax | PHP in_array()

The syntax for the in_array() function is straightforward.

in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] ): boolean

Parameters

  • The first parameter is $needle, the value we want to search for in the array. 
  • The second parameter is $haystack, the array we want to search in. 
  • The third optional parameter is $strict, a Boolean value determining whether the comparison should be made strictly (type and value must match) or loosely (only value needs to match). 

Return Type

The function returns true if the value exists in the array and false otherwise.

PHP in_array code example

<?php


$value = 2; //Value to be searched.


$array = array(1, 2, 3, 4, 5); //Array to search the value in.




//in_array() returns true if the value exists.
if (in_array($value, $array)) {
 echo "Value exists in array";
} else {
 echo "Value does not exist in array";
}


//Output
//Value exists in array


?>

In this example, we define a variable $value with the value 2 and an array $array with the values 1, 2, 3, 4, and 5. 

We then use the in_array() function to check if the value 2 exists in the array. Since 2 is in the array, the function returns true and prints “Value exists in array”.

Check if a value exists in an array using PHP in_array()

Let’s look at another example to demonstrate how to check if an array contains a specific value.

<?php


$fruits = array("apple", "banana", "orange", "grape");


if (in_array("apple", $fruits)) {
 echo "I love apples!";
} else {
 echo "No apples for me.";
}


//Output
//I love apples!


?>

In this example, we define an array $fruits with the values “apple”, “banana”, “orange”, and “grape.” 

We then use the in_array() function to check if the value “apple” exists in the array.

 Since “apple” is in the array, the function returns true and prints the message “I love apples!”

Check if a value exists in a multi-dimensional array using PHP in_array() | Iterative Approach

The in_array() function can check if a value exists in a multi-dimensional array. 

in_array php

Let’s take a look at an example that uses a foreach loop to iterate over a multi-dimensional array.

<?php


$people = array(
   array("name" => "John", "age" => 30),
   array("name" => "Mary", "age" => 25),
   array("name" => "Peter", "age" => 40)
);
 //Needle 
$search_name = "Mary";
$search_age = 35;


//Iterate over the multi-dimensional array
foreach ($people as $person) {
 //$person is array inside the people array.
 if (in_array($search_name, $person)) {
   echo $search_name . " is in the array!";
 }
 if (in_array($search_age, $person)) {
   echo $search_age . " is in the array!";
 }
}


//Output
//Mary is in the array!


?>

In this example, we define a multi-dimensional array $people with three sub-arrays, each containing a person’s name and age. 

We then define two variables, $search_name, and $search_age, with values to search for in the array. 

We use a foreach loop to iterate over each sub-array in $people. The in_array() function checks if $search_name or $search_age exists for each sub-array. If the value exists, the example prints a message.

Limitation of the iterative approach

Iterative approaches with multi-dimensional arrays have limitations that can impact the code’s performance and readability. 

  1. Iterating through a multi-dimensional array using loops can result in complex and difficult-to-read code.
  1. Can be slower for searching large multi-dimensional arrays, especially if the array has many nested levels.
  1. May only be suitable for some types of searches. For example, if we want to search for values in a non-numeric array or search for values using complex criteria, a more specialized search function can be helpful instead.
  1. Require careful handling to avoid errors. If we are not careful, we can easily introduce bugs into the code that can be difficult to diagnose and fix.

Overall, iterative approaches with multi-dimensional arrays can be useful in certain situations, but they have limitations. For more complex searches or larger arrays, recursive algorithms or more specialized search functions may be a better option.

Check if a value exists in a multi-dimensional array using PHP in_array() | Recursive Approach

In a recursive algorithm, a function calls itself unless it hits a stopping criteria. Such algorithms generalize well and help improve performance and increase efficiency for larger, more complex arrays.

in_array php

 Here’s an example of using in_array() recursively for a multi-dimensional array.

<?php


$students = array(
 array("name" => "John", "age" => 20, "courses" => array("Math", "Science")),
 array("name" => "Mary", "age" => 22, "courses" => array("History", "English")),
 array("name" => "Peter", "age" => 24, "courses" => array("Computer Science", "Physics"))
);


function searchArray($needle, $haystack) {
 foreach($haystack as $value) {
   //If array within array
   if(is_array($value)) {
     //Recursively call the function on the array.
     if(searchArray($needle, $value)) {
       return true;
     }
   } else {
     if(in_array($needle, $haystack)) {
       return true;
     }
   }
 }
 return false;
}


$search_course = "Physics";


foreach ($students as $student) {
 //Search if a student is enrolled in Physics.
 if (searchArray($search_course, $student)) {
   echo "Course found for " . $student['name'];
 } else {
   echo "Course not found for " . $student['name'];
 }
}


/*
OUTPUT
Course not found for John
Course not found for Mary
Course found for Peter
*/

?>

In this example, we have a multi-dimensional array $students, with each sub-array containing a student’s name, age, and a nested array of courses they are taking. 

We define a recursive function searchArray() that takes a needle (the value we’re searching for) and a haystack (the array we’re searching in). The function iterates over each value in the haystack and checks if it is an array. 

  • If it is, the function is called recursively with the current value as the haystack.
  •  If it is not an array, in_array() is used to check if the needle exists in the current value. 

The function returns true if the needle is found in the haystack and false otherwise.

We then define a variable $search_course with the value “Physics” and use a foreach loop to iterate over each sub-array in $students

We call each sub-array searchArray() with $search_course as the needle and the sub-array as the haystack. 

  • If the course is found for a student, a message is printed indicating that the course was found for that student. 
  • If the course is not found, a message indicates that the course was not found for that student.

Recursive algorithms are hard to get at first, but they are really a treat for cracking similar problems and those involving more complex data structures like graphs and trees.

Benefits of the recursive approach

  1. Recursive algorithms can break down complex problems into simpler sub-problems. Each recursive call solves a smaller part of the problem, leading to a simpler overall solution.
  1. Recursive algorithms can be more readable than iterative algorithms for certain problems. The recursive approach often requires less code, making it easier to understand and maintain.
  1. In some cases, recursive algorithms can be more efficient than iterative algorithms. The recursive approach can avoid unnecessary processing and reduce the algorithm’s time complexity.
  1. Recursive algorithms can often manage memory more efficiently than iterative algorithms. This is because the recursive approach uses the call stack to manage function calls and local variables, which can reduce the amount of memory the algorithm requires.
  1. Recursive algorithms apply to a wide range of problems in computer science, such as sorting, searching, and traversal. They help implement more advanced data structures, such as trees and graphs.

Overall, recursive algorithms can be a powerful tool for solving complex problems and improving the efficiency and readability of our code.

Case-insensitive Search with in_array() PHP?

To perform a case-insensitive search, you can pass the strtolower() function as the third argument to in_array(), which converts the search string to lowercase. Here’s an example.

<?php

$values = array('Apple', 'Banana', 'Orange');
$searchValue = 'apple';

if (in_array(strtolower($searchValue), array_map('strtolower', $values), true)) {
    echo "The array contains the value $searchValue (case-insensitive search).";
} else {
    echo "The array does not contain the value $searchValue (case-insensitive search).";
}

?>

In this example, the strtolower() function converts the $searchValue to lowercase, and the array_map() function converts all elements in the $values array to lowercase. 

The third argument of in_array() is set to true, which performs a strict comparison, where the type of the value is also considered. This ensures that only values with the same type are compared.

Using the in_array function in PHP

The article provides an overview of the in_array() function in PHP, which can be used to search for a specific value within an array. The function syntax is explained, including the optional $strict parameter for performing strict type comparisons. 

The article then covers the basic usage of the function and provides code examples for checking if a single-dimensional and multi-dimensional array contains a specific value.

The article also discusses the limitations of using an iterative approach with multi-dimensional arrays, including code complexity, performance, limited functionality, and potential for errors. Alternatives to iterative approaches are presented, including recursive, array, and custom functions. 

Finally, the benefits of recursive algorithms are discussed, such as simplifying complex problems, improved readability, reduced time complexity, better memory management, and versatility.

PHP Fundamentals Article Series

This article is part of our series on learning the fundamentals of PHP web development. If you are stepping into your PHP journey. Check out the articles in this series to get deeper into PHP.

Learn the Fundamentals of Good Web Development

Please take a moment and sign up for our free email course on the fundamentals of good web development. Every week is packed with a roundup of articles on our site and from around the web, where we go deep into developing exceptional web applications. We have meetups, code reviews, slack chats, and more.

Click here to get started

.