Eun Eun - 8 months ago 57
PHP Question

For-each loop, larger than 20 into another array

I'm stuck on this exercise that I can't seem to get for the life of me.

$numbers2 = [21, 5, 4, 6, 76, 2, 18, 85, 55, 1];

foreach ($numbers2 as &$value) {
$largeNumbers[] = $value > 20;

That's the code I have so far. What I am trying to do here is use a for-each loop to add all the numbers that are larger than 20 into another Array, which I have named $largeNumbers. The code I have inserted above seems to be printing out true and false values, which is not what I was going for. I'd really appreciate it someone could tell me what I'm possibly doing wrong or even show me a better way. I have to use a for-each loop.

Answer Source

For each item, you are checking if it's larger than 20, which results in a boolean value (it either is or is not), and you then store this value to the result array. Instead, you could use an if statement` to only take the elements that answer the condition:

foreach ($numbers2 as &$value) {
    if ($value > 20) {
        $largeNumbers[] = $value;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download