Get the amount of elements higher than a particular one [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have this in my php code:
$aNumbers = array(2,8,9,5.5,4,5.5,6,7,8,9,10,1,'NB');
From this I must determine the amount of values above 5.5 and the average of all numbers combined. Using only a For Loop, if/else construction and the count() function.
I have tried to solve this myself, but nowhere on the internet I can find sufficient information.

This should do it:
$aNumbers = array(2,8,9,5.5,4,5.5,6,7,8,9,10,1,'NB');
const HIGH_VALUE_CUTOFF = 5.5;
$uncleanArrayCount = count($aNumbers);
$cleanArray = array();
$highValueCount = 0;
$sum = 0;
for ($i = 0; $i < $uncleanArrayCount; $i++) {
if ($aNumbers[$i] > 0) { // catch only numbers
$sum += $aNumbers[$i];
$cleanArray[] = $aNumbers[$i]; // builds an array of numbers
}
if ($aNumbers[$i] > HIGH_VALUE_CUTOFF) {
$highValueCount++;
}
}
$average = $sum / count($cleanArray);
echo "Average: $average <br />";
echo "Numbers above " . HIGH_VALUE_CUTOFF . ": $highValueCount";
Next time, post what you've tried. 'Twas fun doing your homework for you!

Try something like this:
<?php
$sum = 0;
$amount = 0;
$aNumbers = array(2, 8, 9, 5.5, 4, 5.5, 6, 7, 8, 9, 10, 1, 'NB');
foreach ($aNumbers as $value){
if($value > 5){
$sum += $value;
$amount++;
}
}
echo "Sum : " . $sum . " - Average : ". ($sum / $amount);
?>

Related

Nested Loops headache PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How would you go about answering a question like this? I know I would have to use a loop, but my current answer won't allow me to go over an input of about 5 which is incredibly inefficient. I'm finding nested loops a little daunting.
Given the triangle of consecutive odd numbers:
1
3 5
7 9 11
...
Calculate the row sums of this triangle from the row index (starting at index 1)
rowSumOddNumbers(1); // 1
rowSumOddNumbers(2); // 3 + 5 = 8
Disclaimer - this is not a test questions. Just one of the practice ones I'm struggling to get my head around.
Since posting this I have found a working answer (three hours later...)
Working code:
function rowSumOddNum($n) {
$start = ($n *($n - 1)) + 1;
$sum = 0;
$step = $start +($n*2);
for($a=$start;$a<$step;$a++){
if($a % 2 !== 0){
$sum = $sum + $a;
}
} echo $sum;
}
This was the original code I was working with that kept crashing out saying it didn't have enough memory. Very inefficient I believe.
function rowSumOddNumbers($n) {
$len = $n + ($n*1);
$array = [];
for ($i = 1; $i <= $len; $i+2) {
if ($i % 2 == 1) {
$array[] = $i;
}
}
$count = 0;
$answer = 0;
for ($row = 1; $row < $n; $row++) {
$count = $count + $row;
}
$length = $count + $n;
for ($a = $count; $a <$length; $a++) {
$answer = $answer + $array[$a];
}
echo $answer;
}
I liked the challenge, so here it is.
This should do the job no matter how big the triangle is.
<?php
$triangle = array(1,5,11,9,7,3);
$u = 1;
$results = array();
$sumrow =0;
for($i=0; $i<=count($triangle); $i++){
if($i == count($triangle)){
$sumrow += $triangle[0]; // for the last row add the first number of array
}else{
$sumrow += $triangle[$i];
}
if(is_int($u/3)){ // for every third number store results and use the same number again
$i--;
$u = 1;
array_push($results, $sumrow);
$sumrow = 0;
}else{
$u++;
}
}
echo json_encode($results);
?>

is it possible in php loop without nested loop [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to print like this using loop without nested loop:
1
2 3
4 5 6 7
8 9 10 11 12 13 14 15
first line start from 1 and print only one integer
second line start from 2 and print two integer
third line start from 4 and print four integer
fourth line start from 8 and print eight integer
(same condition in other line if exist)
A pair of counters should do the trick;
$threshold = 1;
$x = 1;
for($i = 1; $i <= 15; $i++) {
echo $i . ' ';
if($x == $threshold) {
echo "<br>\n";
$threshold = $threshold * 2;
$x = 0;
}
$x++;
}
Will keep on working till infinity, or your script runs out of memory. Whatever comes first :)
You can achieve with single while and some array functions. Try this.
<?php
$start=1;
while($start<=10){
$array = range($start,($start+$start-1));
echo implode(' ',$array)."<br>";
$start=$start*2;
}
?>
something like this?
$i=1;
$t=1;
while($i<1000)
{
if($i==$t)
{
if($t!=1) echo "<br />";
$t=$t*2;
}
echo $i." ";
$i++;
}
same thing but with log($i,2).
<?php
$i=1;
while($i<20)
{
echo $i;
$i++;
if(filter_var(log($i,2), FILTER_VALIDATE_INT))
echo PHP_EOL;
else
echo "\t";
}
You can even do it without any for and some recursion ;-)
<?php
$elements = range(1,15);
display($elements);
function display(array $parts, $step = 1) {
if(! count($parts)) {
return;
}
$elements = array_splice($parts, 0, $step);
echo implode("\t", $elements)."\n";
display($parts, $step * 2);
}
See the working code on https://eval.in/755277

PHP: How to remove comma in a for loop? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
<?php
for ($i = 10; $i < 101; $i = $i + 10) {
echo $i;
}
?>
I'm starting to learn PHP and this is the code I'm working on. What I'm trying to do is remove the comma on the last item that will display (e.g. 10, 20, 30, 40, 50, 60, 70, 80, 90, 100,) I've searched the forum and all I see are methods for "foreach"...Any suggestions, replies are appreciated.
You could do something like this,
$result = array();
for ( $i = 10; $i < 101; $i = $i + 10 ){
$result[] = $i;
}
echo implode(", ", $result);
This should work!
There is no comma in your code or it's output but your question is still understandable and you just missed posting the code line which outputs those commas. You simply have to check if this is the last iteration of the loop and if so don't print comma
echo $i;
if($i<100) //currently you don't have this check so you get an extra comma
echo ",";
Output
10,20,30,40,50,60,70,80,90,100
Try this:
$result = array();
for ($i = 10; $i < 101; $i += 10) {
$result[] = $i;
}
echo implode(", ", $result);
If it's an array, write implode(',', $array). If it's not, save output from each iteration to a variable(say $output), then, write substr($output,0,-1).
$output = "";
for ($i = 10; $i < 101; $i = $i + 10) {
$output .= $i.",";
}
echo substr($output,0,-1);
Your code doesn't relate to your question/description, though!

a sum of some values in an php array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have this array`
<?php
$arr = [['name'=>'john','age'=>20,'sex'=>'m'],
['name'=>'maria','age'=>12,'sex'=>'f'],
['name'=>'nick','age'=>25,'sex'=>'m'],
['name'=>'jo','age'=>31,'sex'=>'f'],];
foreach ($arr as $persoana) {
foreach ($persoana as $id=>$value) {
if ($id == 'age') {
$sumvarsta = $sumvarsta + $value;
$n++;
}
}
}`?>
i need total average age (total average age seems to be working ok) , average age for women and average age for men.
How to calculate ?
thx.
<?php
$arr = [['name'=>'john','age'=>20,'sex'=>'m'],
['name'=>'maria','age'=>12,'sex'=>'f'],
['name'=>'nick','age'=>25,'sex'=>'m'],
['name'=>'jo','age'=>31,'sex'=>'f'],];
$womansum = 0;
$womancount = 0;
$mansum = 0;
$mancount = 0;
foreach ($arr as $persoana) {
if ($persoana['sex'] == 'm')
{
$mansum += $persoana['age'];
$mancount++;
} else {
$womansum += $persoana['age'];
$womancount++;
}
}
$manAverage = $mansum / $mancount;
$womanAverage = $womansum / $womancount;
$totalAverage = ($mansum + $womansum) / ($mancount + $womancount);
?>

How to increment a for loop by more than 1? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
How do I print a series like this?
6,15,24,33,42.....1000
I have tried using a for loop like this, but can't work out how to get it to increment by 9 on each iteration.
for($i = 6; $i <= 1000; $i = 9)
{
echo $i . ', ';
}
Quite simple really:-
for($i = 6; $i <= 1000; $i += 9){
echo $i . ', ';
}
//If you have to finish the series with 1000, although it is not a part of the series:-
echo '1000';
See it working
just for fun:
echo implode(', ', range(6, 1000, 9));
echo ", 1000";
<?php
for($i=6; $i<1000; $i+=9)
echo $i."<br>";
?>
Seeing the question this can be an answer.

Categories