-2

i want to print the values of variables in an array but nothing appears, can someone help ?

<?php

$i = 0;
$array = array();
function addInArray($var, $array) {
    $array[] = $var;
}
while ($i < 10) {
    ${"char" . $i} = 1;
    addInArray(${"char" . $i}, $array);
    foreach ($array as $values) {
        echo $values.PHP_EOL;
    }
    $i++;
}

?>
  • Your `$array` var inside `addInArray` is a copy of the one you pass as parameter. See [Passing by Reference](https://www.php.net/manual/en/language.references.pass.php). – Jeto Dec 10 '19 at 20:51
  • Why do you need a function for that? And if you do for some reason, why not just use `array_push`? – Don't Panic Dec 10 '19 at 20:53
  • 3
    Looks like some form of exercise code as `${"char" . $i} = 1;` just seems like a useless way of doing this. – Nigel Ren Dec 10 '19 at 20:55
  • Thanks a lot for your quick answers, i just used array_push and it worked well, in fact i'm not sure i'm doing this the right way but i'll see. – Etienne BURONFOSSE Dec 10 '19 at 20:59

1 Answers1

2

Check Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?. You either need to pass by reference &:

$i = 0;
$array = array();
function addInArray($var, &$array) { //HERE
    $array[] = $var;
}

while ($i < 10) {
    ${"char" . $i} = 1;
    addInArray(${"char" . $i}, $array);
    foreach ($array as $values) {
        echo $values.PHP_EOL;
    }
    $i++;
}

Or return the array from the function:

$i = 0;
$array = array();
function addInArray($var, $array) {
    $array[] = $var;
    return $array;  //HERE
}

while ($i < 10) {
    ${"char" . $i} = 1;
    $array = addInArray(${"char" . $i}, $array); ??HERE
    foreach ($array as $values) {
        echo $values.PHP_EOL;
    }
    $i++;
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87