I have to count the numbers which is divisible by 5.
Here is my code,
$num = array(4, 25, 60, 7, 8);
foreach ($num as $numbers) {
if (($numbers % 5) == 0) {
echo count($numbers);
}
}
Output of above program is 11. But output should be 2. Please give me solution. Thanks in advance.
$nums = array(4, 25, 60, 7, 8);
To only count:
-Basic:
$count = 0;
foreach ($nums as $num) {
if ( $num % 5 == 0 ) $count++;
}
-Playing with types:
$count = 0;
foreach ($nums as $num) {
$count += !($num % 5);
}
$num % 5 returns an integer, !($num % 5) returns a boolean but since it is used as operand with the + operator, false and true act like 0 and 1.
-Functional version using array_reduce:
$count = array_reduce($nums, function($c, $i) { return $c + !($i % 5); });
To filter items, use the well named array_filter:
$result = array_filter($nums, function ($i) { return $i % 5 == 0; });
and count the number of items after if you want:
$count = count($result);
You can use this way also,
function divisibleby5($var){
return $var % 5 == 0;
}
$num = array(4, 25, 60, 7, 8);
echo count(array_filter($num,'divisibleby5');
I think you need to do something more like the following perhaps.
$num = array(4, 25, 60, 7, 8);
$numbers=array();
foreach( $num as $number ) {
if( $number % 5 == 0 ) $numbers[]=$number;
}
echo count( $numbers );
or alternatively using array_walk and a custom callback function
function mod5($item,$key,$arr){
if($item %5==0)$arr[]=$item;
}
array_walk( $num,'mod5',&$numbers);
echo count($numbers);
Here Output is 1 and 1. Not 11 (eleven)
You can try it
echo count($numbers)."<br>";
your solution:
Output will be 2 if you increment count variable value after enter the if condition
<?php
$num = array(4, 25, 60, 7, 8);
$count = 0;
foreach($num as $numbers) {
if (($numbers % 5) == 0) {
$count++;
}
}
echo $count;
?>
in the event you want to print the numbers also
$a=array(); //initialized empty array
$num = array(4, 25, 60, 7, 8);
foreach($num as $numbers){
if(($numbers % 5) == 0){
$a=$numbers; //store values into the array
}
}
echo count($a); // echo the count of the array
echo implode('<br>',$a);
OR if you just need the count
$a=0; //initalize $a
$num = array(4, 25, 60, 7, 8);
foreach($num as $numbers){
if(($numbers % 5) == 0){
$a++; //increment a
}
}
echo $a
Related
My task is to create a loop that displays all even numbers in a column and it also displays a sum of all odd numbers in an array.
So far I have made this:
<?php
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
foreach ($numbers as $index=>$value) {
if ($value % 2 == 0)
echo "$value <br>";
}
?>
This code successfully displays a list of all even numbers. However, I still have to include a sum of all odd numbers that is displayed below the list of evens. For some reason, I am supposed to use a variable $sumOdd = 0.
How do I approach this from here on?
<?php
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$sumOdd = 0;
foreach ($numbers as $index=>$value) {
if ($value % 2 == 0)
echo "$value <br>";
} else {
$sumOdd += $value
}
}
echo $sumOdd;
To do it backwards: add all numbers, take out the even ones
<?php
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$sum = array_sum($numbers);
foreach ($numbers as $index=>$value) {
if ($value % 2 == 0)
echo "$value <br>";
$sum = $sum - $value;
}
echo 'odds: '. $sum;
?>
heyo,
the $sumOdd = 0; should be before the foreach, inside the foreach you will do another check and if it's odd you add the number on $sumOdd += $value
this is a short and cleaner answer :
$sumOdd = 0;
foreach (range(1, 10) as $number) {
if (0 === $number % 2) {
echo $number . '<br>';
continue;
}
$sumOdd += $number;
}
echo '<br> sumOdd = '.$sumOdd;
A better way to calculate the sum is to pass the result of array_filter to array_sum. By doing that, you separate the tasks (calculate, display) and the code becomes more clean and maintainable.
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$sumOdd = array_sum(array_filter($numbers, function($v) {
return $v % 2 !== 0;
}));
I am trying to get highest number from array. But not getting it. I have to get highest number from the array using for loop.
<?php
$a =array(1, 44, 5, 6, 68, 9);
$res=$a[0];
for($i=0; $i<=count($a); $i++){
if($res>$a[$i]){
$res=$a[$i];
}
}
?>
I have to use for loop as i explained above. Wat is wrong with it?
This should work for you:
<?php
$a = array(1, 44, 5, 6, 68, 9);
$res = 0;
foreach($a as $v) {
if($res < $v)
$res = $v;
}
echo $res;
?>
Output:
68
In your example you just did 2 things wrong:
$a = array(1, 44, 5, 6, 68, 9);
$res = $a[0];
for($i = 0; $i <= count($a); $i++) {
//^ equal is too much gives you an offset!
if($res > $a[$i]){
//^ Wrong condition change it to <
$res=$a[$i];
}
}
EDIT:
With a for loop:
$a = array(1, 44, 5, 6, 68, 9);
$res = 0;
for($count = 0; $count < count($a); $count++) {
if($res < $a[$count])
$res = $a[$count];
}
What about:
<?php
$res = max(array(1,44,5,6,68,9));
(docs)
you should only remove the = from $i<=count so it should be
<?php $a =array(1,44,5,6,68,9);
$res=$a[0];
for($i=0;$i<count($a);$i++){
if($res<$a[$i]){
$res=$a[$i];
}
}
?>
the problem is that your loop goes after your arrays index and the condition is reversed.
The max() function will do what you need to do :
$res = max($a);
More details here.
Suggest using Ternary Operator
(Condition) ? (True Statement) : (False Statement);
<?php
$items = array(1, 44, 5, 6, 68, 9);
$max = 0;
foreach($items as $item) {
$max = ($max < $item)?$item:$max;
}
echo $max;
?>
Suppose I have a multidimensional array
$num1 = array(1, 4, 6, 12, 15, 16, 21, 34, 25, 29);
$num2 = array(1, 5, 18, 19, 23, 19, 23, 45, 23, 16);
$array = array($num1, $num2);
I want to extract all the values from $array where the $array[0] values meet some condition e.g. have a value between 10 & 20.
to get the required values from $array I can use this code:
$count = count($array[0]);
$new_array = array_fill(0, $count, array());
for($i = 0; $i < $count; $i++)
{
if($array[0][$i] >= 10 && $array[0][$i] <= 20)
{
$new_array[0][] = $array[0][$i];
$new_array[1][] = $array[1][$i];
}
}
//I get the array that I need
print_r($new_array);
This is the code I need to change every time
$array[0][$i] >= 10 && $array[0][$i] <= 20 (condition --> values from the first sub array are >= 10 and <= 20)
result would be
Array(0 => Array(0 => 12, 1 => 15, 2 => 16), 1 => Array(0 => 19, 1 => 23, 2 => 19))
another condition
$array[1][$i] >= 20 && $array[1][$i] <= 30 (condition --> values from the second sub array are >= 20 and <= 30)
result would be
Array(0 => Array(0 => 15, 1 => 21, 2 => 25), 1 => Array(0 => 23, 1 => 23, 2 => 23))
I need to do such operations with different columns using different conditions. So, instead of writing code for looping every time, I want to create a function with condition as an argument. Is it possible, if so how?
I would like to have a function with three arguments as shown below
function_name ($array, $column_num, $condition)
Any alternative solutions are also welcome.... :)
Code I used finally to get this done....
<?php
function mdarray_condition_extract($array, $column, $condition)
{
$count = count($array[0]);
$nsac = count($array);
$new_array = array_fill(0, $nsac, array());
for ($i = 0; $i < $count; $i++)
{
$valToTest = $array[$column][$i];
if ($condition($valToTest))
{
for($k = 0; $k < $nsac; $k++)
{
$new_array[$k][] = $array[$k][$i];
}
}
}
return $new_array;
}
$array = array(array(1, 4, 6, 12, 15, 16), array(1, 5, 18, 19, 23, 19));
$columns = array(0,1,0);
$conditions = [
0 => function($val){return $val >= 10 && $val <= 20;},
1 => function($val){return $val >= 20 && $val <= 30;},
2 => function($val){return $val == 6 || $val == 20;}
];
$combo = array($columns, $conditions);
$condcount = count($combo[0]);
for($i = 0; $i < $condcount; $i++)
{
print_r(mdarray_condition_extract($array, $combo[0][$i], $combo[1][$i])); echo "<br><br>";
}
?>
Thanks all for the response, it helped me in a great way...!!
Your existing code is very close.
function filterParallelArrays($array, $predicateFilterIndex, $predicate)
{
$count = count($array[0]);
$new_array = array_fill(0, $count, array());
for ($i = 0; $i < $count; $i++)
{
$valToTest = $array[$predicateFilterIndex][$i];
if ($predicate($valToTest))
{
$new_array[0][] = $array[0][$i];
$new_array[1][] = $array[1][$i];
}
}
return $new_array;
}
$predicate = function($val)
{
return $val >= 10 && $val <= 20;
};
print_r(filterParallelArrays($array, 0, $predicate));
You question is about filtering your arrays. For that, PHP has built-in function array_filter() . It takes callback for filtering values.
If I got your question correctly, you want to apply filter to your sub-arrays - and, probably, with different conditions. Normally, if do that statically, it is:
$array[0] = array_filter($array[0], function($x)
{
return $x>=10 && $x<=20; //item between 10 and 20
});
-but if you have predefined list for each column, you can fill a map:
$conditions = [
//column index => condition callback:
0 => function($x){ return $x>=10 && $x<=20; },
1 => function($x){ return $x==50 || $x==80; },
//e t.c.
];
foreach($array as $key=>$column)
{
if(array_key_exists($key, $conditions))
{
$array[$key] = array_filter($array[$key], $conditions[$key]);
}
}
So, using array_filter() - you can do it natively, I think you won't need your own custom function to do this (because wrapping native function has little sense in this case).
Given your latest update, you could do something like this. But I'm still not really sure what your objective is here, so this might be totally out to lunch.
function array_function($key, $lcond, $rcond)
{
$count = count($array[0]);
$new_array = array_fill(0, $count, array());
for($i = 0; $i < $count; $i++)
{
if($array[$key][$i] >= $lcond && $array[$key][$i] <= $rcond)
{
$new_array[0][] = $array[0][$i];
$new_array[1][] = $array[$key][$i];
}
}
//I get the array that I need
return $new_array;
}
This question already has answers here:
PHP get the item in an array that has the most duplicates
(2 answers)
Closed 1 year ago.
I have an array of numbers like this:
$array = array(1,1,1,4,3,1);
How do I get the count of most repeated value?
This should work:
$count=array_count_values($array);//Counts the values in the array, returns associatve array
arsort($count);//Sort it from highest to lowest
$keys=array_keys($count);//Split the array so we can find the most occuring key
echo "The most occuring value is $keys[0][1] with $keys[0][0] occurences."
I think array_count_values function can be useful to you. Look at this manual for details : http://php.net/manual/en/function.array-count-values.php
You can count the number of occurrences of values in an array with array_count_values:
$counts = array_count_values($array);
Then just do a reverse sort on the counts:
arsort($counts);
Then check the top value to get your mode.
$mode = key($counts);
If your array contains strings or integers only you can use array_count_values and arsort:
$array = array(1, 1, 1, 4, 3, 1);
$counts = array_count_values($array);
arsort($counts);
That would leave the most used element as the first one of $counts. You can get the count amount and value afterwards.
It is important to note that if there are several elements with the same amount of occurrences in the original array I can't say for sure which one you will get. Everything depends on the implementations of array_count_values and arsort. You will need to thoroughly test this to prevent bugs afterwards if you need any particular one, don't make any assumptions.
If you need any particular one, you'd may be better off not using arsort and write the reduction loop yourself.
$array = array(1, 1, 1, 4, 3, 1);
/* Our return values, with some useless defaults */
$max = 0;
$max_item = $array[0];
$counts = array_count_values($array);
foreach ($counts as $value => $amount) {
if ($amount > $max) {
$max = $amount;
$max_item = $value;
}
}
After the foreach loop, $max_item contains the last item that appears the most in the original array as long as array_count_values returns the elements in the order they are found (which appears to be the case based on the example of the documentation). You can get the first item to appear the most in your original array by using a non-strict comparison ($amount >= $max instead of $amount > $max).
You could even get all elements tied for the maximum amount of occurrences this way:
$array = array(1, 1, 1, 4, 3, 1);
/* Our return values */
$max = 0;
$max_items = array();
$counts = array_count_values($array);
foreach ($counts as $value => $amount) {
if ($amount > $max) {
$max = $amount;
$max_items = array($value);
} elif ($amount = $max) {
$max_items[] = $value;
}
}
$vals = array_count_values($arr);
asort($vals);
//you may need this end($vals);
echo key($vals);
I cant remember if asort sorts asc or desc by default, you can see the comment in the code.
<?php
$arrrand = '$arr = array(';
for ($i = 0; $i < 100000; $i++)
{
$arrrand .= rand(0, 1000) . ',';
}
$arrrand = substr($arrrand, 0, -1);
$arrrand .= ');';
eval($arrrand);
$start1 = microtime();
$count = array_count_values($arr);
$end1 = microtime();
echo $end1 - $start1;
echo '<br>';
$start2 = microtime();
$tmparr = array();
foreach ($arr as $key => $value);
{
if (isset($tmparr[$value]))
{
$tmparr[$value]++;
} else
{
$tmparr[$value] = 1;
}
}
$end2 = microtime();
echo $end2 - $start2;
Here check both solutions:
1 by array_count_values()
and one by hand.
<?php
$input = array(1,2,2,2,8,9);
$output = array();
$maxElement = 0;
for($i=0;$i<count($input);$i++) {
$count = 0;
for ($j = 0; $j < count($input); $j++) {
if ($input[$i] == $input[$j]) {
$count++;
}
}
if($count>$maxElement){
$maxElement = $count;
$a = $input[$i];
}
}
echo $a.' -> '.$maxElement;
The output will be 2 -> 3
$arrays = array(1, 2, 2, 2, 3, 1); // sample array
$count=array_count_values($arrays); // getting repeated value with count
asort($count); // sorting array
$key=key($count);
echo $arrays[$key]; // get most repeated value from array
String S;
Scanner in = new Scanner(System.in);
System.out.println("Enter the String: ");
S = in.nextLine();
int count =1;
int max = 1;
char maxChar=S.charAt(0);
for(int i=1; i <S.length(); i++)
{
count = S.charAt(i) == S.charAt(i - 1) ? (count + 1):1;
if(count > max)
{
max = count;
maxChar = S.charAt(i);
}
}
System.out.println("Longest run: "+max+", for the character "+maxChar);
here is the solution
class TestClass {
public $keyVal;
public $keyPlace = 0;
//put your code here
public function maxused_num($array) {
$temp = array();
$tempval = array();
$r = 0;
for ($i = 0; $i <= count($array) - 1; $i++) {
$r = 0;
for ($j = 0; $j <= count($array) - 1; $j++) {
if ($array[$i] == $array[$j]) {
$r = $r + 1;
}
}
$tempval[$i] = $r;
$temp[$i] = $array[$i];
}
//fetch max value
$max = 0;
for ($i = 0; $i <= count($tempval) - 1; $i++) {
if ($tempval[$i] > $max) {
$max = $tempval[$i];
}
}
//get value
for ($i = 0; $i <= count($tempval) - 1; $i++) {
if ($tempval[$i] == $max) {
$this->keyVal = $tempval[$i];
$this->keyPlace = $i;
break;
}
}
// 1.place holder on array $this->keyPlace;
// 2.number of reapeats $this->keyVal;
return $array[$this->keyPlace];
}
}
$catch = new TestClass();
$array = array(1, 1, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3, 1, 2, 3, 1, 1, 2, 5, 7, 1, 9, 0, 11, 22, 1, 1, 22, 22, 35, 66, 1, 1, 1);
echo $catch->maxused_num($array);
I have an array of numbers and some numbers are obviously too big or too small relative to them all. I wonder if there is already some kind of function or algorithm that I can use in order to remove these records from array.
Here is an example of array
8
7
21
1330829238608
6
7
188
8
25
92433
19
6
At the moment all I can think about is just check if number is more than 1k or less than 1k and then do not allow it. But still I get problem since 188 does not belong here either.
Is there any good way that I can get majority of close numbers from this array and produce something like
8
7
6
7
8
6
This is what I have so far
<?php
echo '<pre>';
$startArray = Array(8, 7, 21, 1330829238608, 6, 7, 188, 8, 25, 92433, 19, 6);
print_r($startArray);
for ($i = 0; $i < count($startArray); $i++) {
if ($i != count($startArray) - 1) {
if ($startArray[$i] - 10 <= $startArray[$i + 1]) {
echo $startArray[$i] . '<br />';
}
}
}
Use array_filter:
function filter_callback($var){
return $var < 100 && $var > 2;
}
$array = array(1,1000,23,4453,123,412,321,433,4,6,2,3,5,634,32,432,45,3,4);
$filtered = array_filter($array, "filter_callback");
$arrayData = array(8, 7, 21,
1330829238608,
6, 7, 188, 8, 25,
92433,
19, 6,
);
$min = 7;
$max = 10;
$matches = array_filter( $arrayData,
function($data) use ($min,$max) {
return (($data >= $min) && ($data <= $max));
}
);
var_dump($matches);
I really gotta go but it's an easy one.
create a maximum = closest number to 0 in the array, multiplied by $delta.
any number in the array smaller than the maximum from pct. 1, but if multiplied by $delta is greater than that maximum, becomes maximum if($i<$max && $i*$delta>$max) $max = $i*$delta
trim out all numbers bigger than the current maximum.
Problem is you need a $delta. It's safe to go with 2 for delta, but if you want it adaptable don't ask me how to do it because that's cognitive neuroscience.
This can be optimized but this is what I figured out, works with diff of 20%, you can change it to whatever % you want, of course.
<?php
$startArray = array(8, 7, 21, 1330829238608, 6, 7, 188, 8, 25, 92433, 19, 6);
$groupArray = array();
$startArrayCount = count($startArray);
for ($i = 0; $i < $startArrayCount; $i++) {
// 20% of current value
$valueDiff = ($startArray[$i] / 100) * 20;
// Get minimal and maximal value
$maxValue = ($startArray[$i] + $valueDiff);
$minValue = ($startArray[$i] - $valueDiff);
// Print it out
// echo 'Diff: ' . $valueDiff . '<br />';
// echo 'Max: ' . $maxValue . '<br />';
// echo 'Min: ' . $minValue . '<br />';
$groupArray[$i] = array();
for ($n = 0; $n < $startArrayCount; $n++) {
if ($startArray[$n] <= $maxValue && $startArray[$n] >= $minValue) {
// echo 'TRUE: ' . $startArray[$n] . '<br />';
array_push($groupArray[$i], $startArray[$n]);
}
}
//echo '<hr />';
}
// Getting arrays that have most members in it
$max = count($groupArray[0]);
foreach ($groupArray as $group) {
if (count($group) > $max) {
$max = count($group);
}
}
// Taking all those arrays and combining them in one
$finishArray = array();
foreach ($groupArray as $group) {
if (count($group) == $max) {
foreach ($group as $key) {
array_push($finishArray, $key);
}
}
}
// Combining all values
$total = null;
foreach ($finishArray as $num) {
$total = $total + $num;
}
// Getting average
$average = $total / count($finishArray);
echo $average;