Search code examples
phpfunctioncsvexplodeimplode

PHP: Format variable by predetermined CSV order... but Why this code as function breaks?


This code works perfectly... but why I got error using it as PHP function?

$name = '1 value';
$age  = '2 value';
$date = '3 value';

$string = "date, name, age"; //default CSV file Column order

Will get great results:

date, name, age

date|name|age
3 value|1 value|2 value|

By using this code:

echo $string.'<br/>'; 

echo implode("|", explode(", ", $string)).'<br/><br/>';

    $line='';
    foreach(explode(", ", $string) as $str)    {
            $line .= $$str.'|';
    }
    echo $line;

I code this function:

<?php
function toImplode($string)
{
    $line = '';
    foreach (explode(", ", $string) as $str) {
        $line .= $$str . '|';
    }
    return $line;
}

echo 'Variable to line formatted order is:<br/> ' . toImplode($string) . '<br/>';

But I got this error:

> Notice: Undefined variable: name in on line 22 
> Notice: Undefined variable: age in on line 22 
> Notice: Undefined variable: date in on line 22

I can't understand why.


Solution

  • You can use the global keyword with variable variables ($$):

    Add the following line into the function body

    global $$str; 
    

    So the full code becomes:

    <?php
    
    $name = '1 value';
    $age  = '2 value';
    $date = '3 value';
    $string = "date, name, age";
    
    function toImplode($string) { $line=''; foreach(explode(", ", $string) as $str){ global $$str; $line .= $$str.'|';} return $line;} 
    
    echo 'Variable to line formatted order is: '.toImplode($string).'<br/>';
    

    Output:

    Variable to line formatted order is: 3 value|1 value|2 value|<br/>
    

    Try it online!