0

I have variables like $start1,$start2...$start($no_col). How can I show all the variables with echo in php? in the code below it doesn't work. $no_col can change from 1 to 10. it is not fixed! I want the result show me all $start1,$start2... $start($no_col) values. All the $start1 ..$start10 variable contain date like 2022-12-10;

        for ($i=1; $i <=$no_col ; $i++) { 
            echo $start.${$i};

The result will be like this: 2022-03-10 2022-09-06 ...

  • `echo ${'start' . $i};` – 0stone0 Nov 23 '22 at 17:15
  • Is there any reason why you are not using an array for the values instead? – Nigel Ren Nov 23 '22 at 17:24
  • 1
    Or `echo ${"start{$i}"}`, if you don't want concatenation in the middle. But yeah, while this syntax is interesting, you can do the same thing with an array: `$starts = [1 => '2022-03-10', 2 => '2022-09-06']` (etc, or similar), then `$starts[$i]`. – Tim Lewis Nov 23 '22 at 17:25

1 Answers1

1

You can use get_defined_vars function for get all variables, and after that show only what you need:

  <?php
    $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

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39