PHP counter excluding zeros - php

In PHP I have an array that returns a set of values. I want to count the number of instances in the array excluding the zeros. Basically I'm creating an average total column in a table and if a person did not contribute then I don't want to count them. I have the total amount, just not the total count that contributes. Any help please?

You can do it with count and array_filter method.
count gives you the total number of elements in an array.
array_filter removes all elements whose value represents false(such as 0 empty string etc.) from an array;
Eg:
echo count(array_filter($your_array));

Use foreach to iterate the array and count the items that are not "zero".
$counter = 0;
foreach ($array as $item) {
if ( /* determine if $item is "not zero" */ ) {
++$counter;
}
}
echo $counter;
That's all I can tell you based on the information you provided.

You can give a callback function to array_filter as the second parameter. (http://php.net/manual/en/function.array-filter.php)
array array_filter ( array $array [, callable $callback [, int $flag = 0 ]] )
So you can do something like this:
function isNonZero(int $num){
return $num !== 0;
}
count(array_filter([0,1,2,3,4], "isNonZero")); // => 4

Related

count the elements in array except of specific element

For example i have an array like this [-1,-1,-1,-1,-1,-1,2.5,-1,-1,8.3]
I want to count the element which are not -1 like except of the -1. Is there any function in php to get this ? One approach which i think is
Count the total array - count of the -1 in the array.
how can we achieve this.
P.S : please provide me a comment why this question deserve negative vote.
Like #MarkBaker said, PHP doesn't have a convenient function for every single problem, however, you could make one yourself like this:
$arr = [-1,-1,-1,-1,-1,-1,2.5,-1,-1,8.3];
function countExcludingValuesOfNegativeOne ($arr) {
return count($arr) - array_count_values(array_map('strval', $arr))['-1'];
}
echo countExcludingValuesOfNegativeOne($arr); // Outputs `2`.
It just counts the whole array, then subtracts the number of negative 1s in the array. Because PHP throws an error if any element in the array isn't a string 1 when using array_count_values, I've just converted all elements of the array to a string using array_map('strval', $arr) 2
you can use a for loop counter skipping for a specific number.
function skip_counter($array,$skip){
$counter = 0;
foreach ($array as $value) {
if ($value != $skip) $counter++;
}
return $counter;
}
then you call skip_counter($your_list, $number_to_be_skipped);

Get the highest number value 'Magento'

I have this function and i want to get the highest number value.
$array is out-putting 20, 50, 40.
I want to print 50 only not the other 2.
Tried everything nothing is working.
foreach ($products as $product) {
$originalPriceCat = $product->getPrice();
$finalPriceCat = $product->getFinalPrice();
if ($originalPriceCat > $finalPriceCat) {
$CalculatedPrice = ($originalPriceCat - $finalPriceCat) * 100 /$originalPriceCat;
$array = array($CalculatedPrice);
echo round(max($array));
}
}
The following code will surely solve your problem
$CalculatedPrice = array();
foreach ($products as $product) {
$originalPriceCat = $product->getPrice();
$finalPriceCat = $product->getFinalPrice();
if ($originalPriceCat > $finalPriceCat) {
$CalculatedPrice[] = ($originalPriceCat - $finalPriceCat) * 100 / $originalPriceCat;
}
}
echo round(max($CalculatedPrice));
Take a look at this php function: max
max ( array $values ) : mixed
max ( mixed $value1 [, mixed $... ] ) : mixed
If the first and only parameter is an array, max() returns the highest
value in that array. If at least two parameters are provided, max()
returns the biggest of these values.
max() returns the parameter value considered "highest" according to standard comparisons.
If multiple values of different types evaluate as equal (e.g. 0 and 'abc') the first provided to the function will be returned.
If an empty array is passed, then FALSE will be returned and an E_WARNING error will be emitted.

Find shortest array count in multidimensional array

I have a multidimensional array:
$arr = array(
array('lions', 'tigers', 'bears'), // count = 3
array('dogs', 'cats'), // count = 2
array('horses', 'pigs', 'cattle', 'sheep', 'chickens') // count = 5
);
I want to return the array with the lowest count (I don't need to know the count, just need the array that HAS the lowest count). In this case, array('dogs', 'cats')
Right now I have:
$lowest = null;
foreach($nodePath as $arr)
{
$lowest = count($arr) < count($lowest) || $lowest == null ? $arr : $lowest;
}
This works but I'm wondering if I missed a more contained solution, perhaps using array_map, array_walk or a similar function.
Use array_map() with count as a callback to get the number of elements in each array, min() to get the smallest value. Then, to get the key of the smallest array - use array_flip() to flip the arrays keys and values, and access the $minth index. Now you can use the key to get the array you need:
$counts = array_map('count', $arr);
$min = min($counts);
$key = array_flip($counts)[$min];
$smallest_arr = $arr[$key];
Demo
Map your array to another array with counts of each child array. Get the key of the minimum value in this new array. Smallest array has the key of the minimum value:
$count = array_map('count', $arr);
$min = array_keys($count , min($count))[0];
var_dump($arr[$min]); // Array ( [0] => dogs [1] => cats )
Eval.in

How to deal with an array of equal values and max function?

In PHP, max() returns the highest value in an array or the greatest value among inputs. If we have two or more equally greatest values, how to deal with that situation?
eg
$arr = array("a"=>1,"b"=>10, "c"=>10);
now, what should max($arr), return. Ideally it returns the first encountered highest value, b. What if I want both b and c as result?
If you have the highest value in that array (that is, what max() returns), you can just search for all occurrences of that value in the array:
$arrOfKeys = array_keys($arr, max($arr));
max() returns the maximum value, not the array key it is associated with. It will simply return (int) 10 in the example you give.
If you want a list of the keys that have the maximum value you could do something like this:
$max = max($array);
$maxKeys = array();
foreach ($array as $key => $val) {
if ($val == $max) {
$maxKeys[] = $key;
}
}
print_r($maxKeys);
/*
Array
(
[0] => b
[1] => c
)
*/

PHP: How do I check the contents of an array for my string?

I a string that is coming from my database table say $needle.
If te needle is not in my array, then I want to add it to my array.
If it IS in my array then so long as it is in only twice, then I still
want to add it to my array (so three times will be the maximum)
In order to check to see is if $needle is in my $haystack array, do I
need to loop through the array with strpos() or is there a quicker method ?
There are many needles in the table so I start by looping through
the select result.
This is the schematic of what I am trying to do...
$haystack = array();
while( $row = mysql_fetch_assoc($result)) {
$needle = $row['data'];
$num = no. of times $needle is in $haystack // $haystack is an array
if ($num < 3 ) {
$$haystack[] = $needle; // hopfully this adds the needle
}
} // end while. Get next needle.
Does anyone know how do I do this bit:
$num = no. of times $needle is in $haystack
thanks
You can use array_count_values() to first generate a map containing the frequency for each value, and then only increment the value if the value count in the map was < 3, for instance:
$original_values_count = array_count_values($values);
foreach ($values as $value)
if ($original_values_count[$value] < 3)
$values[] = $value;
As looping cannot be completely avoided, I'd say it's a good idea to opt for using a native PHP function in terms of speed, compared to looping all values manually.
Did you mean array_count_values() to return the occurrences of all the unique values?
<?php
$a=array("Cat","Dog","Horse","Dog");
print_r(array_count_values($a));
?>
The output of the code above will be:
Array (
[Cat] => 1,
[Dog] => 2,
[Horse] => 1
)
There is also array_map() function, which applies given function to every element of array.
Maybe something like the following? Just changing Miek's code a little.
$haystack_count = array_count_values($haystack);
if ($haystack_count[$needle] < 3)
$haystack[] = $needle;

Categories