-1

I am using print_r on a variable which gives me the following output

    Array
(
    [0] => 95.2
    [1] => 94.7
    [2] => 95
    [3] => 33.6
)
Array
(
    [0] => 100
    [1] => 95
    [2] => 91.90000000000001
    [3] => 33.6        
)

I want to split them into two variable dynamically. Like $var1 and $var2. If there were three iterations, i would want it to be three variables. Is it possible in php? In the current scenario i want

$var1=  (
        [0] => 95.2,
        [1] => 94.7,
        [2] => 95,
        [3] => 33.6
    )

and

$var2=  (
        [0] => 100,
    [1] => 95,
    [2] => 91.90000000000001,
    [3] => 33.6  
    )

and i want to both to be generated dynamically and if possible i want the count of the iterations as well. Thank you in advance

  • 1
    Wh-- no… why!? Leave them in the array. – deceze Apr 17 '18 at 10:49
  • i want to split them in two variables and them add them up and get the average – Heisenberg Apr 17 '18 at 11:05
  • You don't need to split them into two variables to add the values and get an average. What's the difference between doing `$var1` and `$var2`, and `$vars[0]` and `$vars[1]`? You can already do the latter one with the values in an array. – deceze Apr 17 '18 at 11:06

1 Answers1

0
<?php
$data[]=array(1,2,3);
$data[]=array(5,6,7);
$data[]=array(7,8,9);
//you can add many more here and it will still works fine



foreach ($data as $key=>$value){
    $variable_name='var_'.$key;
    $$variable_name=$value;
}

print_r($var_0);
print_r($var_1);
print_r($var_2);

Sure it is possible.

Wils
  • 1,178
  • 8
  • 24
  • 1
    But now, how you gonna know how many `$var_` variables there are in your scope…? You can't `count()` them. And you can't hardcode their names beforehand, because you don't know beforehand how many there will be… → Don't do this. – deceze Apr 17 '18 at 10:55
  • It's not hardcode. I am hardcoding the sample data. – Wils Apr 17 '18 at 10:58
  • if your $data length increases, the foreach loop will create more variable. that's what the question is asking. – Wils Apr 17 '18 at 11:00
  • I'm saying, how will you be able to write `print_r($var_2)` at the end? Do you know whether there will be a `$var_2`? How? Will there be a `$var_42` as well? What if there isn't but you've hardcoded `print_r($var_42)`? – deceze Apr 17 '18 at 11:01
  • Sir, I am doing a demo output. How and when and what the questioner wants to show is their choice. – Wils Apr 17 '18 at 11:02
  • I'm trying to tell both you and @Heisenberg that the real answer to the question is *Don't do it this way.* – deceze Apr 17 '18 at 11:03
  • I have modified the question to let you know what exactly i want. If it is possible then please help me. – Heisenberg Apr 17 '18 at 11:08