Home >Backend Development >PHP Tutorial >How to Convert Array Values to Lowercase in PHP?

How to Convert Array Values to Lowercase in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-10-20 07:43:29874browse

How to Convert Array Values to Lowercase in PHP?

Converting Array Values to Lowercase in PHP

In PHP, converting array values to lowercase is essential for standardizing data and facilitating comparison. One method to achieve this is through array_map().

Using array_map() to Lowercase Values

To lowercase all values in an array using array_map(), follow these steps:

  1. Specify the array you want to process and assign it to a variable.
  2. Call array_map() and provide two arguments:

    • The function to apply to each value. In this case, 'strtolower'.
    • The array to be processed.

For example, consider the following array:

<code class="php">$array = ['apple', 'orange', 'banana'];</code>

To convert all values to lowercase:

<code class="php">$lowercaseArray = array_map('strtolower', $array);</code>

The resulting $lowercaseArray will contain:

<code class="php">['apple', 'orange', 'banana']</code>

Lowercasing Nested Arrays

If you have a nested array, you may want to lowercase values in all levels. To do this, you can use a recursive function:

<code class="php">function nestedLowercase($value) {
    if (is_array($value)) {
        return array_map('nestedLowercase', $value);
    }
    return strtolower($value);
}</code>

To use this function, apply it to the $yourArray variable as follows:

<code class="php">$yourArray = array_map('nestedLowercase', $yourArray);</code>

The above is the detailed content of How to Convert Array Values to Lowercase in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn