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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.