Searching and Filtering Arrays in PHP Practice Questions with Solutions

Introduction

PHP provides useful functions to search for specific values, check whether an element exists, and filter arrays based on conditions. These operations are commonly used when finding employees, checking product availability, identifying student marks, and processing records. In this chapter, you will practise in_array(), array_search(), array_key_exists(), array_filter(), and other useful array-searching techniques through practical solved questions. Searching and Filtering Arrays in PHP Practice questions with solutions to help you to understand the concepts.

Question 1: Check Whether a Value Exists Using in_array()

Problem Statement

Create an array of programming languages and check whether “Python” exists using the in_array() function.

PHP Solution

<?php
$languages = ["PHP", "Java", "Python", "C++", "JavaScript"];

if (in_array("Python", $languages)) {
    echo "Python is available in the array.";
} else {
    echo "Python is not available in the array.";
}
?>

Sample Output

Python is available in the array.

Explanation

The in_array() function checks whether a specified value exists in an array. It returns true if the value is found and false otherwise.

Concepts Covered

  • in_array() function
  • Searching array values
  • if-else statement
  • Boolean results

Question 2: Find the Position of a Value Using array_search()

Problem Statement

Create an array containing employee names and find the index of “Neha” using the array_search() function.

PHP Solution

<?php
$employees = ["Rahul", "Amit", "Neha", "Priya", "Karan"];

$position = array_search("Neha", $employees);

if ($position !== false) {
    echo "Neha found at index: " . $position;
} else {
    echo "Employee not found.";
}
?>

Sample Output

Neha found at index: 2

Explanation

The array_search() function searches for a value and returns its corresponding key or index. If the value is not found, it returns false. The strict comparison !== false correctly handles cases where the matching index is 0.

Concepts Covered

  • array_search() function
  • Finding array indexes
  • Strict comparison
  • Handling missing values

Question 3: Search for a Key Using array_key_exists()

Problem Statement

Create an associative array containing employee details. Check whether the key "salary" exists using array_key_exists().

PHP Solution

<?php
$employee = [
    "name" => "Rahul",
    "department" => "IT",
    "salary" => 35000
];

if (array_key_exists("salary", $employee)) {
    echo "Salary information is available.";
} else {
    echo "Salary information is not available.";
}
?>

Sample Output

Salary information is available.

Explanation

The array_key_exists() function checks whether a specified key exists in an array. It checks for the key even when its associated value is null.

Concepts Covered

  • array_key_exists() function
  • Associative arrays
  • Searching array keys
  • Conditional statements

Question 4: Filter Students Who Passed an Exam Using array_filter()

Problem Statement

Create an associative array containing student names and marks. Use array_filter() to display students who scored 40 or more marks.

PHP Solution

<?php
$students = [
    "Rahul" => 75,
    "Priya" => 35,
    "Amit" => 82,
    "Neha" => 28,
    "Karan" => 60
];

$passedStudents = array_filter($students, function ($marks) {
    return $marks >= 40;
});

print_r($passedStudents);
?>

Sample Output

Array
(
    [Rahul] => 75
    [Amit] => 82
    [Karan] => 60
)

Explanation

The array_filter() function checks every value using the supplied callback function. Only students with marks greater than or equal to 40 are included in the new array. Their original keys are preserved.

Concepts Covered

  • array_filter() function
  • Callback functions
  • Filtering associative arrays
  • Conditional expressions

Question 5: Filter Products Within a Price Range

Problem Statement

Create an array of product prices. Use array_filter() to display products costing between ₹500 and ₹2,000.

PHP Solution

<?php
$prices = [300, 750, 1200, 2500, 1800, 450];

$filteredPrices = array_filter($prices, function ($price) {
    return $price >= 500 && $price <= 2000;
});

print_r($filteredPrices);
?>

Sample Output

Array
(
    [1] => 750
    [2] => 1200
    [4] => 1800
)

Explanation

The callback function checks whether each price falls within the given range. Only matching values are returned. The original indexes are preserved, which is why the output contains indexes 1, 2, and 4.

Concepts Covered

  • array_filter() function
  • Filtering numeric values
  • Logical AND operator
  • Price range conditions

Question 6: Search for an Employee by Name in an Associative Array

Problem Statement

Create an associative array containing employee names and departments. Search for an employee named “Priya” and display her department.

PHP Solution

<?php
$employees = [
    "Rahul" => "IT",
    "Amit" => "Sales",
    "Priya" => "HR",
    "Neha" => "Finance"
];

$searchName = "Priya";

if (array_key_exists($searchName, $employees)) {
    echo $searchName . " works in " . $employees[$searchName] . " department.";
} else {
    echo "Employee not found.";
}
?>

Sample Output

Priya works in HR department.

Explanation

The array_key_exists() function checks whether the employee name is present as a key. If the key exists, its corresponding department is accessed using $employees[$searchName].

Concepts Covered

  • Associative array searching
  • array_key_exists() function
  • Accessing values using keys
  • Conditional statements

Question 7: Filter Employees Based on Salary

Problem Statement

Create an associative array containing employee names and salaries. Use array_filter() to display employees earning more than ₹30,000.

PHP Solution

<?php
$employees = [
    "Rahul" => 25000,
    "Priya" => 42000,
    "Amit" => 35000,
    "Neha" => 28000,
    "Karan" => 50000
];

$highSalaryEmployees = array_filter($employees, function ($salary) {
    return $salary > 30000;
});

print_r($highSalaryEmployees);
?>

Sample Output

Array
(
    [Priya] => 42000
    [Amit] => 35000
    [Karan] => 50000
)

Explanation

The array_filter() function checks each employee’s salary. Employees earning more than ₹30,000 are included in the result. The original employee names are preserved as array keys.

Concepts Covered

  • Filtering associative arrays
  • array_filter() function
  • Salary conditions
  • Callback functions

Question 8: Find All Matching Values Using array_keys()

Problem Statement

Create an array containing product categories. Find all indexes where the category "Electronics" appears using the array_keys() function.

PHP Solution

<?php
$categories = [
    "Electronics",
    "Clothing",
    "Electronics",
    "Furniture",
    "Books",
    "Electronics"
];

$positions = array_keys($categories, "Electronics");

print_r($positions);
?>

Sample Output

Array
(
    [0] => 0
    [1] => 2
    [2] => 5
)

Explanation

The array_keys() function normally returns all keys from an array. When you provide a second argument, it returns only the keys whose values match the specified value. Here, it finds every position containing "Electronics".

Concepts Covered

  • array_keys() function
  • Searching multiple matches
  • Finding array indexes
  • Indexed arrays

Question 9: Filter Products That Are In Stock

Problem Statement

Create a multidimensional array containing product names and stock quantities. Use array_filter() to display only products with stock greater than zero.

PHP Solution

<?php
$products = [
    [
        "name" => "Laptop",
        "stock" => 10
    ],
    [
        "name" => "Mouse",
        "stock" => 0
    ],
    [
        "name" => "Keyboard",
        "stock" => 15
    ],
    [
        "name" => "Monitor",
        "stock" => 0
    ]
];

$availableProducts = array_filter($products, function ($product) {
    return $product["stock"] > 0;
});

print_r($availableProducts);
?>

Sample Output

Array
(
    [0] => Array
        (
            [name] => Laptop
            [stock] => 10
        )

    [2] => Array
        (
            [name] => Keyboard
            [stock] => 15
        )
)

Explanation

The callback function checks the "stock" value of each product. Products with stock greater than zero are included in the filtered array. The original indexes are preserved.

Concepts Covered

  • Multidimensional arrays
  • array_filter() function
  • Filtering nested records
  • Callback functions

Question 10: Filter Students Who Scored 60 or More Marks and Reindex the Result

Problem Statement

Create an array containing student marks. Use array_filter() to select students who scored at least 60 marks. Then use array_values() to reset the indexes.

PHP Solution

<?php
$marks = [85, 45, 72, 30, 90, 55];

$qualifiedMarks = array_filter($marks, function ($mark) {
    return $mark >= 60;
});

$qualifiedMarks = array_values($qualifiedMarks);

print_r($qualifiedMarks);
?>

Sample Output

Array
(
    [0] => 85
    [1] => 72
    [2] => 90
)

Explanation

First, array_filter() selects marks greater than or equal to 60. It preserves the original indexes. Next, array_values() creates a new indexed array with sequential indexes starting from 0.

Concepts Covered

  • array_filter() function
  • array_values() function
  • Filtering numeric arrays
  • Reindexing arrays

Key Takeaways

  • Use in_array() to check whether a value exists in an array.
  • Use array_search() to find the key or index of a matching value.
  • Use array_key_exists() to check whether a key exists.
  • Use array_filter() to create a new array containing elements that meet a condition.
  • Use array_keys() with a search value to find all matching keys.
  • Use callback functions to define custom filtering conditions.
  • array_filter() preserves the original array keys.
  • Use array_values() when you want to reset numeric indexes after filtering.
  • You can search and filter indexed, associative, and multidimensional arrays.

Frequently Asked Questions (FAQs)

1. How do you search for a value in a PHP array?

Use the in_array() function to check whether a particular value exists in an array.

2. What is the difference between in_array() and array_search()?

in_array() returns true or false depending on whether a value exists. array_search() returns the matching key or index, or false if no match is found.

3. What does array_filter() do in PHP?

The array_filter() function creates a new array containing only the elements that satisfy a specified condition.

4. How do you check whether a key exists in an associative array?

Use array_key_exists() to check whether a specified key exists, even if its value is null.

5. Does array_filter() change the original array?

No. It returns a filtered array and leaves the original array unchanged.

6. Does array_filter() preserve array indexes?

Yes. It preserves the original keys of the elements that pass the filtering condition.

7. How do you reset array indexes after filtering?

Use array_values() on the filtered array to create sequential numeric indexes starting from 0.

8. Can array_filter() work with associative arrays?

Yes. It can filter associative arrays and preserve their original keys.

9. Can we search for multiple matching values in an array?

Yes. You can use array_keys() with a search value to get all keys where that value occurs in the array.

10. Can we filter a multidimensional array in PHP?

Yes. Use array_filter() with a callback function that checks the required fields inside each nested array.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top