Search code examples
phploopsvariablesencode

How to easily overwrite/change multiple php variables


I'm building a pdf with php and noticed that my strings didn't work, because they were in the UTF-8 Format. utf8_decode($str) works fine but I have plenty of variables that I would have to decode this way. My code looks something like this:

function makePDF(titleStr, bodyStr, headerStr, and more...)
{

   //TO-DO

   $pdf->Cell(20, 6, $titleStr, 1, 1, 'L', false);
   $pdf->Cell(15, 6, $bodyStr, 1, 1, 'L', true);
   $pdf->Cell(50, 6, $headerStr, 1, 1, 'R', false);
}

I want to find a way to decode them all at once in a loop or something without having to do this for each variable or changing any other code that I already have:

$titleStr = utf8_decode($titleStr);
$bodyStr  = utf8_decode($bodyStr);
...and so on

Anyone an idea how to do this more easily?


Solution

  • You can read all of your function's arguments with func_get_args() to retrieve them, array_map() to apply the UTF8 decoding, and list() read them back into simple string variables.

    <?php
    
    function makePDF($titleStr, $bodyStr, $headerStr)
    {
        $args = func_get_args();
    
        $args = array_map(function($args){
            return utf8_decode($args);
        }, $args);
    
        list($titleStr, $bodyStr, $headerStr) = $args;
    
        var_dump($titleStr);
        var_dump($bodyStr);
        var_dump($headerStr);
    }
    
    makePDF('foo', 'bar', 'baz');
    

    Outputs:

    string(3) "foo" 
    string(3) "bar" 
    string(3) "baz"
    

    You will need to copy/paste your method signature into the list() call, but that's fairly simple.


    For fun, if you want to skip the copy/paste step, you can switch in func_get_args() for get_defined_vars() and use variable variables to reassign the arguments:

    <?php
    
    function makePDF($titleStr, $bodyStr, $headerStr)
    {
        $args = get_defined_vars();
    
        $args = array_map(function($args){
            return utf8_decode($args) . rand(0,10);
        }, $args);
    
        foreach($args as $key => $arg){
            // The two $$ show that this is a variable variable.
            $$key = $arg;
        }
    
        var_dump($titleStr);
        var_dump($bodyStr);
        var_dump($headerStr);
    }
    
    makePDF('foo', 'bar', 'baz');
    
    string(4) "foo5"
    string(4) "bar5"
    string(4) "baz9"
    

    *I've added rand() in the array_map() callable to demonstrate that the assignment is actually taking place here.