Lowercase each arguments of a function

Viewed 108

I need to lowercase each arguments of my function.

function somefunc($a, $b, $c, $d, $e, $f, $g) {
    $a = mb_strtolower($a);
    $b = mb_strtolower($b);
    $c = mb_strtolower($c);
    $d = mb_strtolower($d);
    $e = mb_strtolower($e);
    $f = mb_strtolower($f);
    $g = mb_strtolower($g);
}

I tried this but it doesn't work properly:

function somefunc($a, $b, $c, $d, $e, $f, $g) {
    $args = func_get_args();
    foreach($args as $h) {
        $h=mb_strtolower($h);
    }
}

How should I do?

5 Answers
function somefunc($a, $b, $c, $d, $e, $f, $g) {
    $args = array_map('mb_strtolower', func_get_args());

You can use also next function:

function all_to_lower(...$args){

    foreach($args as &$arg){
        $arg = strtolower($arg);   // or mb_strtolower
    } 

    return $args;  
}

$out = all_to_lower('TRETE','QQREWR');

print_r($out);

Demo

In your case you need to replace your foreach loop with:

foreach($args as &$arg) {
    $arg = mb_strtolower($arg);
}

You can use this method, first get list of all arguments of a function, the iterate on them and change them.

function somefunc($a, $b, $c, $d, $e, $f, $g) {
    $params = (new ReflectionFunction(__FUNCTION__))->getParameters();
    foreach ($params as $param) {
        ${$param->name} = mb_strtolower(${$param->name});
    }
}

NOTE: when you have a variable name in string, like "a" for example, you can use ${"a"} to point at variable $a.

Modify by reference (no return value) by adding & to each of the incoming parameters of your custom function.

array_walk() complained about iterating these references, so I settled for a classic foreach() loop (which also modifies by reference).

If you print them out... func_get_args() is less cooperative than get_defined_vars() because the former creates an indexed array and the latter creates an associative array which maintains the variable relationships.

Code: (Demo)

function somefunc(&$a, &$b, &$c, &$d, &$e, &$f, &$g) {
    foreach (get_defined_vars() as &$v) {
        $v = mb_strtolower($v);
    }
}

$a = 'HÈllo1';
$b = 'HÈllo2';
$c = 'HÈllo3';
$d = 'HÈllo4';
$e = 'HÈllo5';
$f = 'HÈllo6';
$g = 'HÈllo6';

somefunc($a, $b, $c, $d, $e, $f, $g);
var_export([$a, $b, $c, $d, $e, $f, $g]);

Output:

array (
  0 => 'hèllo1',
  1 => 'hèllo2',
  2 => 'hèllo3',
  3 => 'hèllo4',
  4 => 'hèllo5',
  5 => 'hèllo6',
  6 => 'hèllo6',
)
    function somefunc($a, $b, $c, $d, $e, $f, $g) {
        // get all parameter value with key
        $args = get_defined_vars();
        // loop $args
        foreach($args as $key => $val) {
            // assign lowered $val to variable named from $key value
            ${$key} = mb_strtolower($val);
        }
    }

Demo : https://3v4l.org/EWGVg

Related