Search code examples
phpvariablesdynamic-variables

Swap part of a PHP variable name?


Is something like the following pseudocode possible in PHP?

$backing_type='work';

$work_token='123';
$review_token='456';   

echo ${$backing_type}_token;

//prints '123';

Solution

  • Yes. You can do the following:

    echo ${$backing_type . '_token'};
    

    However, I would consider this messy programming. Using an array would be preferred:

    $arr = array('work' => 123, 'review' => 456);
    echo $arr[$backing_type];