array('B','...">

How to change the depth of an unknown array and change all letters from lower to upper in php array?

$ar = array(10, 102, 199, "a"=>array('B','c','d'=>array('e','f')),'g','h'); 

I want to change all lowercase to uppercase (ABCDEFGH). I tried this:

function toto($arr,$depth='1'){
    $tem=array();
    foreach ($arr as $key => $value) {
        if(is_string($value)){
            $tem[]=strtoupper($value);
        }elseif(is_array($value)&&array_depth($value)>1){
            // $J=str_repeat('[]', (array_depth($value)));
            $tem[]=array_map('strtoupper',$value);
        }else{
            $tem[]=$value;
        }
    }
    return $tem;
}

And I tried to get the depth of the array with this:

function array_depth($array) {
    $max_depth = 1;

    foreach ($array as $value) {
        if (is_array($value)) {
            $depth = array_depth($value) + 1;

            if ($depth > $max_depth) {
                $max_depth = $depth;
            }
        }
    }        
    return $max_depth;
 }

How can I achieve these two things?

+4
source share
3 answers

You can use this single line layer:

$ar = json_decode(strtoupper(json_encode($ar)),true);

it is first encoded by json, then strtouppercalled and decoded as an array again.

This way you get both keys and the upper value .

+1
source

Perhaps a quick look at the PHP documents would show you the array_walk_recursive () function , which allows you to do:

array_walk_recursive(
    $ar,
    function (&$value, $key) {
        $value = strtoupper($value);
    }
);

....

+4

array_map(): -

function to_upper($n)
{
    return(strtoupper($n));
}

$input = array('a','b','c');
$output = array_map("to_upper", $input);
print_r($output);
0

All Articles