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>
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.
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.