How to Search A Multi-Level Array In PHP?

10 minutes read

To search a multi-level array in PHP, you can use recursive functions to traverse through each level of the array until you find the desired value.


Here is an example of a recursive function that searches for a specific value in a multi-level array:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function searchValue($array, $searchValue) {
  foreach($array as $key => $value) {
    if ($value === $searchValue) {
      return true; // Value found
    } elseif (is_array($value)) {
      if (searchValue($value, $searchValue)) {
        return true; // Value found in nested array
      }
    }
  }
  return false; // Value not found
}

// Example usage
$nestedArray = array(
  "level1" => array(
    "level2" => array(
      "level3" => "searchedValue"
    )
  ),
  "otherKey" => "otherValue"
);

$searchValue = "searchedValue";
if (searchValue($nestedArray, $searchValue)) {
  echo "Value found!";
} else {
  echo "Value not found!";
}


In this example, the searchValue function takes two parameters: the array to search through and the value to search for. It iterates through each element of the array and checks if the current value matches the search value. If they match, the function returns true. If the value is an array, the function calls itself recursively to search within that nested array.


By using recursive functions like this, you can effectively search for values within multi-level arrays in PHP.

Best PHP Books to Read in December 2024

1
PHP 8 Objects, Patterns, and Practice: Mastering OO Enhancements, Design Patterns, and Essential Development Tools

Rating is 5 out of 5

PHP 8 Objects, Patterns, and Practice: Mastering OO Enhancements, Design Patterns, and Essential Development Tools

2
PHP & MySQL: Server-side Web Development

Rating is 4.9 out of 5

PHP & MySQL: Server-side Web Development

3
Learning PHP, MySQL & JavaScript: A Step-by-Step Guide to Creating Dynamic Websites (Learning PHP, MYSQL, Javascript, CSS & HTML5)

Rating is 4.8 out of 5

Learning PHP, MySQL & JavaScript: A Step-by-Step Guide to Creating Dynamic Websites (Learning PHP, MYSQL, Javascript, CSS & HTML5)

4
PHP Cookbook: Modern Code Solutions for Professional Developers

Rating is 4.7 out of 5

PHP Cookbook: Modern Code Solutions for Professional Developers

5
PHP: This book includes : PHP Basics for Beginners + PHP security and session management + Advanced PHP functions

Rating is 4.6 out of 5

PHP: This book includes : PHP Basics for Beginners + PHP security and session management + Advanced PHP functions

6
PHP and MySQL Web Development (Developer's Library)

Rating is 4.5 out of 5

PHP and MySQL Web Development (Developer's Library)

7
Murach's PHP and MySQL (4th Edition)

Rating is 4.4 out of 5

Murach's PHP and MySQL (4th Edition)

8
Learning PHP, MySQL & JavaScript: With jQuery, CSS & HTML5 (Learning PHP, MYSQL, Javascript, CSS & HTML5)

Rating is 4.3 out of 5

Learning PHP, MySQL & JavaScript: With jQuery, CSS & HTML5 (Learning PHP, MYSQL, Javascript, CSS & HTML5)

9
Front-End Back-End Development with HTML, CSS, JavaScript, jQuery, PHP, and MySQL

Rating is 4.2 out of 5

Front-End Back-End Development with HTML, CSS, JavaScript, jQuery, PHP, and MySQL


What is the function to flatten a multi-level array in PHP?

In PHP, you can use the array_merge function to flatten a multi-level array. Here is an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
function flattenArray($array) {
    $result = [];

    foreach ($array as $item) {
        if (is_array($item)) {
            $result = array_merge($result, flattenArray($item));
        } else {
            $result[] = $item;
        }
    }

    return $result;
}

// Example usage
$multiLevelArray = [1, [2, 3], [4, [5, 6]], 7];
$flattenedArray = flattenArray($multiLevelArray);
print_r($flattenedArray);


Output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
)



What is the syntax for accessing elements in a multi-level array in PHP?

To access elements in a multi-level array in PHP, you can use square brackets [] and multiple levels of array keys. Here is the syntax:

1
$arrayName['level1']['level2']['level3'];


Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
$students = array(
    'John' => array(
        'age' => 21,
        'grade' => 'A'
    ),
    'Jane' => array(
        'age' => 19,
        'grade' => 'B'
    )
);

echo $students['John']['age']; // Output: 21
echo $students['Jane']['grade']; // Output: B


In the example above, we have a multi-level array named $students. To access elements within it, we use $students['John']['age'] to access John's age, and $students['Jane']['grade'] to access Jane's grade.


How to search for partial matches within a multi-level array in PHP?

To search for partial matches within a multi-level array in PHP, you can use recursive functions. Here's an example of how you can achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
function searchPartialMatches($array, $keyword) {
    $results = [];

    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $subResults = searchPartialMatches($value, $keyword);
            
            if (!empty($subResults)) {
                $results[$key] = $subResults;
            }
        } else {
            if (stripos($value, $keyword) !== false) {
                $results[$key] = $value;
            }
        }
    }

    return $results;
}

// Example usage:
$data = [
    'fruits' => [
        'apple',
        'banana',
        'grape',
    ],
    'animals' => [
        'lion',
        'tiger',
        'elephant',
    ],
    'colors' => [
        'red',
        'blue',
        'green',
    ],
];

$keyword = 'an';
$results = searchPartialMatches($data, $keyword);

print_r($results);


In this example, we have a multi-level array named $data. We want to search for partial matches of the keyword "an" within this array.


The searchPartialMatches() function is a recursive function that iterates through each element of the array. If an element is also an array, it recursively calls itself with that element until we reach a non-array value. If the current value is a non-array value, it checks whether the keyword is present using the stripos() function (which performs a case-insensitive search). If a match is found, it adds the key-value pair to the $results array.


After calling the searchPartialMatches() function with the $data array and the desired $keyword, we print the results using print_r().


The output of the example usage will be:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Array
(
    [fruits] => Array
        (
            [0] => banana
            [2] => grape
        )

    [animals] => Array
        (
            [1] => tiger
            [2] => elephant
        )
)


This output shows the partial matches for the keyword "an" within the multi-level array.


How to delete an element from a multi-level array in PHP?

To delete an element from a multi-level array in PHP, you can use a combination of recursive functions and array manipulation techniques. Here's an example of how you can achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function deleteElement(&$array, $value) {
    foreach ($array as $key => &$element) {
        if ($element === $value) {
            unset($array[$key]); // remove the element
        } elseif (is_array($element)) {
            deleteElement($element, $value); // recursively delete element in sub-arrays
        }
    }
}

// Example usage:
$multiLevelArray = [
    'A' => [
        'B' => 'Value 1',
        'C' => [
            'D' => 'Value 2',
            'E' => 'Value 3',
        ],
        'F' => 'Value 4',
    ],
];

deleteElement($multiLevelArray, 'Value 2');
print_r($multiLevelArray);


In this example, we define a recursive function deleteElement that accepts the multi-level array and the value you want to delete as parameters. It iterates over each element of the array and checks if the element matches the given value. If it does, it uses the unset function to remove the element from the array. If the element is an array itself, it recursively calls the deleteElement function to remove the value from the sub-array.


In the given example, the value 'Value 2' is deleted from the $multiLevelArray and the updated array is printed using print_r.

Facebook Twitter LinkedIn Telegram

Related Posts:

To increase the multi-dimension of an array in TensorFlow, you can use various functions available within the TensorFlow library. Here are the steps you can follow:First, import the TensorFlow module: import tensorflow as tf Create a TensorFlow constant array ...
When it comes to formatting a JSON array in PHP, there are several key considerations to keep in mind. Here is some information on how to properly format a JSON array in PHP:Create an array: Begin by creating an array in PHP. This array will contain the data y...
To save a JSON array in MySQL using PHP, you can follow these steps:Establish a connection to the MySQL database using PHP's mysqli or PDO extension.Convert the JSON array into a PHP array using json_decode(). This will allow easy manipulation and database...