0

So the loop isn't printing and I don't understand why? I'm only a beginner so I'm really confused on why it won't work. If you guys could explain the reason behind it too that would be great.

<html>
<body>
<?php

$numbers = array(4,6,2,22,11);
sort($numbers);

function printarray($numbers, $x) {
    $countarray = count($numbers);
    for($x = 0; $x < $countarray; $x++) {
        echo $numbers[$x];
        echo "<br>"; 
    }    
}

printarray();

?>
</body>
</html>
Thamilhan
  • 13,040
  • 5
  • 37
  • 59
Leo
  • 11
  • 1
    See about variable scope, http://php.net/manual/en/language.variables.scope.php. You aren't passing `$numbers` in.. – chris85 Jan 25 '16 at 04:12
  • Another question that could be solved by an introductory tutorial... – Luke Joshua Park Jan 25 '16 at 04:13
  • 1
    Possible duplicate of [PHP Variable Scope](http://stackoverflow.com/questions/1781780/php-variable-scope), or maybe http://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and. – chris85 Jan 25 '16 at 04:14

2 Answers2

1

You need to add your variable to your function:

printarray($numbers);

You can also remove the $x from the function as it is being created and destroyed in the function itself.

MomasVII
  • 4,641
  • 5
  • 35
  • 52
0

Since you are a beginner, you might be interested in learning about foreach. You can use it to greatly simplify your function like so:

<?php
$numbers = array(4,6,2,22,11);
sort($numbers);

function printArray($nums) {
    foreach($nums as $num) {
        echo $num;
        echo "<br>";
    }    
}

printArray($numbers);

Experiment via: https://3v4l.org/1BtkK

Once you get used to using foreach, take a look at array_map, array_filter, and array_reduce as ways to simplify your code even more.

<?php
$numbers = array(4,6,2,22,11);
$sort($numbers);

function printArray($nums) {
    array_reduce($nums, function ($carry, $item) {
        echo $carry .= $item . "<br>";
    });
}

printArray($numbers);

Experiment via: https://3v4l.org/4JJFL

And since you are a beginner, check out PHP The Right Way and practice. Once you have gained experience, check out PHP The Right Way again and practice some more. And again. And again.

Eric Poe
  • 383
  • 2
  • 9