Example:
$a[] = '56';
$a[] = '66';
$a[] = '';
$a[] = '58';
$a[] = '85';
$a[] = '';
$a[] = '';
$a[] = '76';
$a[] = '';
$a[] = '57';
Actually how to find average value from this array excluding empty. please help to resolve this problem.
first you need to remove empty values, otherwise average will be not accurate.
so
$a = array_filter($a);
$average = array_sum($a)/count($a);
echo $average;
DEMO
More concise and recommended way
$a = array_filter($a);
if(count($a)) {
echo $average = array_sum($a)/count($a);
}
See here
The accepted answer works for the example values, but in general simply using array_filter($a) is probably not a good idea, because it will filter out any actual zero values as well as zero length strings.
Even '0' evaluates to false, so you should use a filter that explicitly excludes zero length strings.
$a = array_filter($a, function($x) { return $x !== ''; });
$average = array_sum($a) / count($a);
echo array_sum($a) / count(array_filter($a));
As a late look, item controls should be done with numeric check. Otherwise something like this $array = [1.2, 0.33, [123]] will corrupt the calculation:
// Get numerics only.
$array = array_filter($array, fn($v) => is_numeric($v));
// Get numerics only where value > 0.
$array = array_filter($array, fn($v) => is_numeric($v) && ($v > 0));
Finally:
public static function average(array $array, bool $includeEmpties = true): float
{
$array = array_filter($array, fn($v) => (
$includeEmpties ? is_numeric($v) : is_numeric($v) && ($v > 0)
));
return array_sum($array) / count($array);
}
Credits: froq.util.Arrays
Related
ok so i have array for example $arr= "/43sdsd555ksldk66sd"544fdfd";
I take numbers using preg_match_all '/\d+/', and array_map('intval', $zni[0]);
Now the problem is i need to reverse those whole int to see if they are symmetric,like 555 and 66 , and if they are GET A TOTAL OF THEM.(total of only symmetric numbers)
i tried to use function " strrev "and got symmetric numbers, but i don't know how to put them in a one place IF THEY ARE symmetric and calculate them.
<?php
$numbers = "";
if (isset($_GET['submit']))
{
$numbers = ($_GET['niz']);
preg_match_all('/\d+/', $numbers, $zni);
$numtwo= array_map('intval', $zni[0]);
}
foreach ($numtwo as $num)
{
$reverse = strrev($num);
var_dump($reverse);
if ($num == $reverse)
{
$reverse = "true";
} else {
$reverse = "false";
}
var_dump($reverse);
}
Since you already got most of the way there and all you were missing basically was to use + or +=, here is an easy example on how to do it:
$input = "/43sdsd555ksldk66sd544fdfd";
$total = 0;
preg_match_all('/\d+/', $input, $m);
foreach ($m[0] as $d)
if ($d == strrev($d))
$total += $d;
var_dump($total); // => int(621)
Using intval() is not necessary as PHP will implicitly cast between types as needed.
Alternatively you can replace the loop with PHP's array_* functions:
$input = "/43sdsd555ksldk66sd544fdfd";
preg_match_all('/\d+/', $input, $m);
$total = array_sum(array_filter($m[0], function ($v) { return $v == strrev($v); }));
var_dump($total); // => int(621)
Here we use an anonymous function with array_filter() to generate a new array that only contains palindrome numbers from the original matches which is then given to array_sum().
So all that's needed to transform your original code into a working example, is introducing a variable and summing up:
<?php
$numbers = "";
if (isset($_GET['submit']))
{
$numbers = ($_GET['niz']);
preg_match_all('/\d+/', $numbers, $zni);
$numtwo= array_map('intval', $zni[0]);
}
$total = 0; // new variable
foreach ($numtwo as $num)
{
$reverse = strrev($num);
var_dump($reverse);
if ($num == $reverse)
{
$reverse = "true";
$total += $num; // sum up
} else {
$reverse = "false";
}
var_dump($reverse);
}
var_dump($total); // => int(621)
I have 2 arrays as follows:
$arr = array('one.jpg', 'two.jpg', 'three.jpg');
$arr1 = array('', 'five.jpg', '');
Now I want to make these two arrays to one array with following value:
$newArray = array('one.jpg', 'five.jpg', 'three.jpg');
How can I do this using PHP?
Use array_filter to remove the empty values.
Use array_replace to replace the values from the first array with the remaining values of the 2nd array.
$arr1=array_filter($arr1);
var_dump(array_replace($arr,$arr1));
Assuming you want to overwrite entries in the first array only with truthy values from the second:
$newArray = array_map(function ($a, $b) { return $b ?: $a; }, $arr, $arr1);
You can iterate through array and check value for second array :
$arr = array('one.jpg', 'two.jpg', 'three.jpg');
$arr1 = array('', 'five.jpg', '');
$newArray =array();
foreach ($arr as $key => $value) {
if(isset($arr1[$key]) && $arr1[$key] != "")
$newArray[$key] = $arr1[$key];
else
$newArray[$key] = $value;
}
var_dump($newArray);
Simple solution using a for loop, not sure whether there is a more elegant one:
$arr = array('one.jpg', 'two.jpg', 'three.jpg');
$arr1 = array('', 'five.jpg', '');
$newArray = array();
$size = count($arr);
for($i = 0; $i < $size; ++$i) {
if(!empty($arr1[$i])){
$newArray[$i] = $arr1[$i];
} else {
$newArray[$i] = $arr[$i];
}
}
There are multiple variables say $a,$b,$c,$d having boolean value.
So what i am trying to do is .
if($a){echo 1;}
if($b){echo 2;}
if($c){echo 3;}
if($d){echo 4;}
and so on.. 50 variables
is there any better way to do this?
Note: More than one variable can be true.
You can use this code to iterate :
$a= $b = $c = TRUE;
$array = array(0=> $a,1=>$b,2=> $c);
foreach($array as $key => $value){
if($value){
echo $key;
}
}
Maybe put all boolean variable inside an boolean array, and iterate the array to check the value
$boolArray = array();
$boolArray[0] = array($a, 1);
$boolArray[1] = array($b, 2);
$boolArray[2] = array($c, 3);
...
for($x = 0; $x < count($boolArray); $x++) {
if ($boolArray[x][1]) {
echo (string)$boolArray[x][2];
}
}
I think you're looking for something like this.
<?php
# Define the settings you already have
$a = true;
$b = true;
$c = true;
# Create an array with letters from a to z
# Instead of this, you can create an array of field names like array('a', 'b', 'c', 'd');
$options = range('a', 'z');
# Loop in the letters from above
foreach($options as $id => $letter) {
# Check if variable exists and boolean is true
if(isset(${$letter}) && ${$letter} === true) {
# Output number from id
echo $id + 1;
}
}
?>
I have wrote this code:
$final = array(
($data[0] - $data[1]),
($data[1] - $data[2]),
($data[2] - $data[3]),
($data[3] - $data[4]),
($data[4] - $data[5]),
($data[5] - $data[6])
);
Some of them will return negative numbers (-13,-42 etc...), how to change the negative ones to 0?
By the way the think i do after is:
$data_string = join(",", $final);
Example: I need to convert it like in the following:
1,3,-14,53,23,-15 => 1,3,0,53,23,0
You can map that:
$zeroed = array_map(function($v) {return max(0, $v);}, $final);
Will set all numbers lower than 0 to 0.
See array_map and max.
Additionally, you can save you some more handwriting with $data:
$final = array_reduce($data, function($v, $w)
{
static $last;
if (null !== $last) $v[] = max(0, $last - $w);
$last = $w;
return $v;
}, array());
$data_string = join(",", $final);
See array_reduce.
Edit: A foreach loop might be easier to follow, I added some comments as well:
// go through all values of data and substract them from each other,
// negative values turned into 0:
$last = NULL; // at first, we don't have a value
$final = array(); // the final array starts empty
foreach($data as $current)
{
$isFirst = $last === NULL; // is this the first value?
$notFirst = !$isFirst;
if ($notFirst)
{
$substraction = $last - $current;
$zeroed = max(0, $substraction);
$final[] = $zeroed;
}
$last = $current; // set last value
}
And here is the demo.
Am guessing this is homework. If so please mark it as such.
Hints:
use a loop instead of hardwired array references.
use an if-statement to check for negative values and switch their sign.
your use of join is correct
I like Hakre's compact answer. However, if you have a more complex requirement, you can use a function:
<?php
$data = array(11,54,25,6,234,9,1);
function getZeroResult($one, $two) {
$result = $one - $two;
$result = $result < 0 ? 0 : $result;
return $result;
}
$final = array(
getZeroResult($data[0], $data[1]),
getZeroResult($data[1], $data[2]),
getZeroResult($data[2], $data[3]),
getZeroResult($data[3], $data[4]),
getZeroResult($data[4], $data[5]),
getZeroResult($data[5], $data[6])
);
print_r($final);
?>
http://codepad.org/viGBYj4f (With an echo to show the $result before test.)
Which gives you:
Array
(
[0] => 0
[1] => 29
[2] => 19
[3] => 0
[4] => 225
[5] => 8
)
Note, you could also just return the ternary:
function getZeroResult($one, $two) {
$result = $one - $two;
return $result < 0 ? 0 : $result;
}
As well as using it in a loop:
<?php
$data = array(11,54,25,6,234,9,1);
function getZeroResult($one, $two) {
$result = $one - $two;
echo "$one - $two = $result\n";
return $result < 0 ? 0 : $result;
}
$c_data = count($data)-1;
$final = array();
for ($i = 0; $i < $c_data; $i++) {
$final[] = getZeroResult($data[$i], $data[$i+1]);
}
print_r($final);
?>
http://codepad.org/31WCbpNr
Say I have this array:
$array[] = 'foo';
$array[] = 'apple';
$array[] = '1234567890;
I want to get the length of the longest string in this array. In this case the longest string is 1234567890 and its length is 10.
Is this possible without looping through the array and checking each element?
try
$maxlen = max(array_map('strlen', $ary));
Sure:
function getmax($array, $cur, $curmax) {
return $cur >= count($array) ? $curmax :
getmax($array, $cur + 1, strlen($array[$cur]) > strlen($array[$curmax])
? $cur : $curmax);
}
$index_of_longest = getmax($my_array, 0, 0);
No loop there. ;-)
A small addition to the ticket. I came here with a similar problem: Often you have to output just the longest string in an array.
For this, you can also use the top solution and extend it a little:
$lengths = array_map('strlen', $ary);
$longestString = $ary[array_search(max($lengths), $lengths)];
Loop through the arrays and use strlen to verify if the current length is longer than the previous.. and save the index of the longest string in a variable and use it later where you need that index.
Something like this..
$longest = 0;
for($i = 0; $i < count($array); $i++)
{
if($i > 0)
{
if(strlen($array[$i]) > strlen($array[$longest]))
{
$longest = $i;
}
}
}
This way you can find the shortest (or longest) element, but not its index.
$shortest = array_reduce($array, function ($a, $b) {
if ($a === null) {
return $b;
}
return strlen($a) < strlen($b) ? $a : $b;
});