Can you use if for the addresses of an array?

Asked

Viewed 297 times

0

What I want to do with the PHP is that each address of an array is compared if it is >= 100 for example do not know if it works if ([0].. [4] >= 100) there is a way to compare all address values with an if ? or if you have something similar thank you (ps : I’ve researched enough and did not find)good people thank you all for the help I managed to solve the problem

  • 1

    Search by array_filter

  • 1

    array_filter seems to me quite unnecessary in something so simple, usually it can be solved within the same for... if the intention is not to reuse the array for something else, for example save this array in a file, database or other format (such as an xml, summarizing, save the data)in practice will almost always be use of unnecessary resource to perform something that often ends up being executed twice. Of course I’m not saying that the function is useless, I’m saying that the use of it for things like this sometimes ends up being an exaggeration.

2 answers

5


If you want to apply a if at a time use a same loop.

for($i = 0; $i < 4; $i++) {
    if($array[$i] >= 100) {
        ...
    }
}


0

As suggested by Anderson Carlos Woss in the comments, the function:

array_filter ( array $array \[, callable $callback \[, int $flag = 0 \]\] ) : array

Filter elements of an array using a callback function. Iterate over each array value by passing them to the callback function. If the callback function returns true, the current array value is returned in the result matrix.

<?php
$numeros = [-25, -16, -9, -4, 0 , 4 , 9 , 16, 25];

echo "Números:" . PHP_EOL;
print_r($numeros);

// Filtra os valores maiores que 0
$positivos = array_filter($numeros, function ($val) {return $val > 0;} );

echo "Números positivos:" . PHP_EOL;
print_r($positivos);

// Aplica a função sqrt(), raíz quadrada, aos valores positivos previamente filtrados
$raizes = array_map('sqrt', $positivos );

echo "Raízes dos números positivos:" . PHP_EOL;
print_r($raizes);

Repl.it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.