Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert array values to lowercase in PHP?

use array_map():

$yourArray = array_map('strtolower', $yourArray);

In case you need to lowercase nested array (by Yahya Uddin):

$yourArray = array_map('nestedLowercase', $yourArray);

function nestedLowercase($value) {
    if (is_array($value)) {
        return array_map('nestedLowercase', $value);
    }
    return strtolower($value);
}

Just for completeness: you may also use array_walk:

array_walk($yourArray, function(&$value)
{
  $value = strtolower($value);
});

From PHP docs:

If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself.

Or directly via foreach loop using references:

foreach($yourArray as &$value)
  $value = strtolower($value);

Note that these two methods change the array "in place", whereas array_map creates and returns a copy of the array, which may not be desirable in case of very large arrays.


You could use array_map(), set the first parameter to 'strtolower' (including the quotes) and the second parameter to $lower_case_array.


If you wish to lowercase all values in an nested array, use the following code:

function nestedLowercase($value) {
    if (is_array($value)) {
        return array_map('nestedLowercase', $value);
    }
    return strtolower($value);
}

So:

[ 'A', 'B', ['C-1', 'C-2'], 'D']

would return:

[ 'a', 'b', ['c-1', 'c-2'], 'd']   

array_change_value_case

by continue

    function array_change_value_case($array, $case = CASE_LOWER){
        if ( ! is_array($array)) return false;
        foreach ($array as $key => &$value){
            if (is_array($value))
            call_user_func_array(__function__, array (&$value, $case ) ) ;
            else
            $array[$key] = ($case == CASE_UPPER )
            ? strtoupper($array[$key])
            : strtolower($array[$key]);
        }
        return $array;
    }


    $arrays = array ( 1 => 'ONE', 2=> 'TWO', 3 => 'THREE',
                     'FOUR' => array ('a' => 'Ahmed', 'b' => 'basem',
                     'c' => 'Continue'),
                      5=> 'FIVE',
                      array('AbCdeF'));


    $change_case = array_change_value_case($arrays, CASE_UPPER);
    echo "<pre>";
    print_r($change_case);
Array
(
 [1] => one
 [2] => two
 [3] => three
 [FOUR] => Array
  (
   [a] => ahmed
   [b] => basem
   [c] => continue
  )

 [5] => five
 [6] => Array
  (
   [0] => abcdef
  )

)

array_map() is the correct method. But, if you want to convert specific array values or all array values to lowercase one by one, you can use strtolower().

for($i=0; $i < count($array1); $i++) {
    $array1[$i] = strtolower($array1[$i]);
}