PHP Tricks
November 23, 2022

How to get all variables by name

Assume we have in our code several variables named as $start1, $start2 .. $startN and we don't know how many such variables we have.

How we can get (print values) of All such variables?

We can do this using get_defined_vars.

This function returns array of all defined variables, and after that we can filter this array only for variables that names starts with "start":


    $start1 = 10;
    $start2 = 20;
    $start3 = 30;
    $start4 = 40;
    $start5 = 50;
    //get all defined vars
    $vars = get_defined_vars();
    foreach($vars as $var=>$val) {
        if (substr($var, 0, 5) == 'start') {
            printf('$%s = %s '. PHP_EOL, $var, $val);

PHPize - online editor