I'm rather new to programming in general. I'm starting off with some exercises but I'm kind of getting stuck. I created an array and looped thru with a foreach loop to print out each individual number stored in the array, but I dont know what to do to find the average of the numbers and print it out.
<?php
$myArray = array(87,75,93,95);
foreach($myArray as $value){
echo "$value <br>";
}
?>
only as an exercise, becuse if you actully wanted to do this you would use #kittykittybangbang's answer
<?php
$myArray = array(87,75,93,95);
$sum='';//create our variable
foreach($myArray as $value){
$sum+=$value; //adds $value to $sum
//echo "$value <br>";
}
echo $sum;
?>
for the count count($myArray); makes the most senses but you could do that in the loop as well:
<?php
$myArray = array(87,75,93,95);
$sum= $count=0;// initiate interger variables
foreach($myArray as $value){
$sum+=$value; //adds $value to $sum
$count++; //add 1 on every loop
}
echo $sum;
echo $count;
//the basic math for any average:
echo $sum/$count;
?>
if you don't create $sum and $count before the loop you would get notices returned from php, as the first time it tried to add to either, there would be noting to add to
You could:
$avg = array_sum($myArray) / count($myArray);
echo $avg;
Where:
array_sum calculates the sum of all elements in the given array.
count outputs the total number of elements in the given array.
Related
I have this code:
// Values of drop-down lists (cmbPosition)
$studPosition = array();
$i = 0;
foreach ($_SESSION['arrayNamePosition'] as $value) {
$studPosition[$i] = $_GET[$value];
$i++;
// Calculates the points for each student in the event
$points = ($_SESSION['noStudents']+1) - $_GET[$value];
echo $points;
$_SESSION['points'] = $points;
}
The code above loops through $_SESSION['arrayNamePosition'] which contains an array. Every thing works but $_SESSION['points'] = $points; is where the problem is (This is the $_SESSION variable which contains $points).
When I echo $points in the current php form, it outputs: 583276
But when I echo $_SESSION['points'] inside a while loop in a different php form it only outputs the last element stored in $echo $_SESSION['points']points which is 6.
How can I fix this so that echo $_SESSION['points'] outputs all the values of $points in a different php form.
NOTE: I have also put echo $_SESSION['points'] inside a for loop but it still outputs the last value stored in $points. e.g. output: 666666
Thanks in advance.
It's because $_SESSION['points'] itself is not an array. You should change your line to:
$_SESSION['points'][] = $points;
Variable points is not an array, therefore it contains only last calculated element. Change it to array, then save each value as new element in array.
I guess you mean that the loop with echo $points; outputs you 583276. Like the $_SESSION['points'], it stores only one value, but you print the value each time.
I would suggest following changes:
$studPosition = array();
$i = 0;
$points = '';
foreach ($_SESSION['arrayNamePosition'] as $value) {
$studPosition[$i] = $_GET[$value];
$i++;
$points = $points.(($_SESSION['noStudents']+1) - $_GET[$value]);
}
echo $points;
$_SESSION['points'] = $points;
How may i know that - In php how many times the foreach loop will get run, before that loop get executed..In other words i want to know the count of that particular loop. I want to apply some different css depends upon the count.
Use the function count to get the amount of numbers in your array.
Example:
$array = array('test1', 'test2');
echo count($array); // Echos '2'
Or if you want to be an engineer for-sorts you can set up something like so:
$array = array('test1', 'test2');
$count = 0;
foreach ($array as $a) { $count++; }
And that can count it for you, and the $count variable will hold the count, hope this helped you.
Simply count() the array and use the output as a condition, like:
if (count($array) > 100) {
// This is an array with more than 100 items, go for plan A
$class = 'large';
} else {
// This is an array with less than 100 items, go for plan B
$class = 'small';
}
foreach ($array as $key => $value) {
echo sprintf('<div id="%s" class="%s">%s</div>', $key, $class, $value);
}
I have an array of about 100 different random number like this:
$numbers=array(10,9,5,12, ..... .... ... ...);
now i want to make an array of random numbers from this array so that addition of selected numbers will be my given number. example: i may ask to get array of numbers such that, if i add all numbers it will be 100.
i am trying to do it in this way,
function rendom_num ($array,$addition)
{
//here is the code
}
print_r (rendome_num ($numbers,100));
i am not able to fiend the code for last 3 days!
Please use shuffle-
<?php
$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
echo "$number ";
}
?>
php.net
can use shuffle as #chatfun said or can try array_rand if want only some random values from your array
$value= array("Rabin","Reid","Cris","KVJ","John");
$rand_keys=array_rand($value,2);
echo "First random element = ".$value[$rand_keys[0]];
echo "<br>Second random element = ".$value[$rand_keys[1]];
Something like this should work. The breakdown is commented so you know what it's all doing.
function Randomizer($number = 100)
{
// This just generates a 100 number array from 1 to 100
for($i=1; $i <= 100; $i++) {
$array[] = $i;
}
// Shuffles the above array (you may already have this array made so you would need to input into this function)
shuffle($array);
// Assign 0 as base sum
$sum = 0;
// Go through the array and add up values
foreach($array as $value) {
// If the sum is not the input value and is also less, continue
if($sum !== $number && $sum < $number) {
// Check that the sum and value are not greater than the input
if(($sum + $value) <= $number) {
// If not, then add
$sum += $value;
$new[] = $value;
}
}
// Return the array when value hit
else
return $new;
}
// If the loop goes through to the end without a successful addition
// Try it all again until it does.
if($sum !== $number)
return Randomizer($number);
}
// Initialize function
$test = Randomizer(100);
echo '<pre>';
// Total (for testing)
echo array_sum($test);
// Array of random values
print_r($test);
echo '</pre>';
I am sure there is a simpler solution to this that I am over looking
Here is some code that basically describes what I am doing:
$array = array('1.4','2.7','4.1','5.9');
$score = '4.4';
foreach($array as $value) {
if($score>$value){
$x = $value;
}
}
foreach($array as $value) {
if($x==$value){
echo $value."<br>";
echo $score."<-- <br>";
} else {
echo $value."<br>";
}
}
Will display as:
1.4
2.7
4.1
4.4<--
5.9
What I am trying to do is print the array values with the score value in order.
Why don't you change the array to actual numerical values and then sort it?
$array = array(1.4, 2.7, 4.1, 5.9);
$score = 4.4;
$array[] = $score;
sort($array);
Or if you need to work with strings:
$array = array('1.4', '2.7', '4.1', '5.9');
$score = '4.4';
$array[] = $score;
sort($array, SORT_NUMERIC);
For sorting, what might be the easiest is to use the sort() method (docs).
You're overwriting $x each time through your first loop. ... the way it's written, when you're done with the first loop, $x has the last value that's less than $score. (Are you identifying a cut-off line?)
After you've sorted with the sort() method, your second loop should work as you intend. There are tighter ways to do the printing (for example, you can implode()), but what you've got should work.
Have an array
array(array('a'=>'s','add'=>1),
array('a'=>'s1','add'=>2),
array('a'=>'s2','add'=>3)
...
...
);
I want to sum of all key add together.so result should be 6
Anyone know how to do this?
$sum = 0;
foreach($yourArray as $element) {
$sum += $element['add'];
}
echo $sum;
$sum = 0;
foreach($array1 as $array) {
$sum += $array['add'];
}
echo $sum; // will echo '6'
Unfortunately, array_sum only works on single-dimensional arrays. Since you're working with an array of associative arrays, you're going to have to approach it differently. If you know your array will have the same form as the one you've linked above, you can simply use something like this:
$total = 0;
foreach( $arrs as $arr )
{
$total += $arr['add'];
}
echo $total;
Where $arrs is the array you've defined above.
One liner echo array_sum(array_column($a, "add"));