Know the total values in the php array

Asked

Viewed 80 times

-5

I need to resolve a situation with the array, it seems to be simple but I’m not getting it!

I have the following array:

$total = array("6.00","7.00","9.5","10","5.5","7.75","6.5","9");

I need to know how many are less than seven. Don’t I want to know what the quantity is? For example: sei que tem o 6.00 o 5.5 e o 6.5. I want you to return total: 3 values.

3 answers

2

Another example of how to use array_filter (as its name already makes clear. A function to filter certain information in the array) and Count (used to count elements), created the function addLessThanSeven(float $val) which receives a value of the type float, and finally returns the values less than 7 (I did no error treatment).

Example:

<?php

    $total = array("6.00", "7.00", "9.5", "10", "5.5", "7.75", "6.5", "9");

    function addLessThanSeven(float $val)
    {
        return ($val < 7);
    }

    echo count(array_filter($total, "addLessThanSeven"));
    //3

1

No need to quote numbers. If used, they will be treated as string.

$total = array(6.00,7.00,9.5,10,5.5,7.75,6.5,9);

$contador = 0;

foreach ($total as $item) 
{
    if($item < 7)
    {
        $contador++;
    }
}

echo "Quantidade de números menores que 7: ".$contador;

1

Utilize array_reduce, that will reduce these array in another type of data with a specific value, in which case the reduction is the counting of items that are less than 7, creating a function sum($a, $b) where the variable value $a is the initial and the value of $b and the value of each position of that array, by checking with a ternary if this value is less than 7 and if satisfied returns the value 1 for accretion or value 0, example:

<?php    

    $total = array("6.00","7.00","9.5","10","5.5","7.75","6.5","9");
    
    function sum($a, $b)
    {
        $a += (float)$b < 7 ? 1 : 0;
        return $a;
    }
    
    echo array_reduce($total, 'sum', 0);

Browser other questions tagged

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