PHP Simple Calculation with an Array - php

So i have a simple for loop to get this result from any given number (get).
1 + 2 + 3 + 4 = 10
$num = intval($_GET["number"]);
$total = 0;
for ($i = 1; $i <= $num; $i++) {
echo $i;
if ($i != $num) {
echo " + ";
}
$total += $i;
}
echo " = " . $total;
Now I want to show the calculation of every step
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
And it should be done with an Array, but I can't seem to figure out the Algorithm.
I think I'm overlooking something simple here.

Try something like this:
<?php
$num = intval($_GET["number"]);
//add all numbers to an array
$numbers = array();
for ($i = 1; $i <= $num; $i++)
{
$numbers[] = $i;
//show each array element with ' + ' in between the elements
echo implode(' + ', $numbers);
//show total sum
echo " = " . array_sum($numbers) . "\n";
}
?>
Note that this does not work, if $_GET['number'] is zero or even below zero.

Here's the simplest way I can think...
$num = intval($_GET['number']);
$intArray = range(1,$num);
echo implode(" + ",$intArray)." = ".array_sum($intArray);

You don't actually need a loop to do an arithmetic progression. An arithmetic progression like this can be calculated in constant time with the formula n * (n[-1] + n[1]) / 2.
For example the progression of 4, where n1 = 1, n2 = 2, n3 = 3, and n4 = 4 is simply 4 * (4 + 1) / 2 == 10.
function progression($n) {
return $n * ($n + 1) / 2;
}
echo progression(4); // 10
However, to show the result of the progression at any given step you simply limit the upper-bound of that progression (i.e. $n).
$n = 4;
for ($i = 1; $i <= $n; $i++) {
$operands = implode('+', range(1, $i));
echo $operands . " = " . progression($i), "\n";
}
output
1 = 1
1+2 = 3
1+2+3 = 6
1+2+3+4 = 10
Generalization
This works for any linear arithmetic progression, regardless of the upper/lower bound. So for example the progression of 5 through 8 is still 4 * (5 + 8) / 2 which gives you 26.
So you can modify this function to a more general solution for any linear arithmetic progression as such.
function progression($size, $start = 1) {
return $size * ($start + ($size + $start - 1)) / 2;
}
$n = 4;
$start = 5;
for ($i = $start; $i <= $n + $start - 1; $i++) {
$operands = implode('+', range($start, $i));
echo $operands . " = " . progression($i - $start + 1, $start), "\n";
}
output
5 = 5
5+6 = 11
5+6+7 = 18
5+6+7+8 = 26

So assuming you are doing a range from the $_GET['number'] number then you can do something like (see comments in code for further explanation):
//This will create an array from 1 to number inclusive
$nums = range(1, $_GET['number']);
//The nums that have been used
$used = array();
//Now loop over that array
foreach($nums as $num){
$used[] = $num; //Add this number to used
if(count($used) > 1){//Dont care about first loop
echo implode(' + ', $used); // put all elements together by + sign
echo ' = ' . array_sum($used) . "<br>"; //Show total plus a break
}
}

<?php
$num = intval($_GET["number"]);
$terms = [1];
for ($i = 2; $i <= $num; $i++) {
$terms[] = $i;
$sum = array_sum($terms);
echo implode(' + ', $terms) . ' = ' . $sum . PHP_EOL;
}

Going for maximum use of PHP array related functions:
$num = intval($_GET["number"]);
$array = range(1, $num);
for ($i = 2; $i <= $num; $i ++)
{
$slice = array_slice($array, 0, $i);
$total = array_sum($slice);
echo implode(" + ", $slice) . " = " . $total . PHP_EOL;
}
Alternative with array_push
$num = intval($_GET["number"]);
$array = array(1);
for ($value = 2; $value <= $num; $value ++)
{
array_push($array, $value);
echo implode(" + ", $array) . " = " . array_sum($array) . PHP_EOL;
}
Output
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10

Related

PHP loop and removing a character from the loop

Im doing a factorial loop test for college but I cannot figure this bit out. I want to do the factorial calculation and echo it but also to remove a bit of the calculation. So i want it to show:
Factorial of 5 is 120
5 x 4 x 3 x 2 x 1 = 120
But what i get is:
Factorial of 5 is 120
5 x 4 x 3 x 2 x 1 x = 120
This is the code I have so far Within php brackets
$i = $num;
do
{
echo strrev(" x $i ");
$i--;
} while($i > 0);
echo (" = $factorial");
You could increase your while() condition by one and add another echo after the loop (Demo), but I don't recommend it.
do-while() looping is not appropriate for your scenario if it is possible that $i = 1. You should use a pre-test loop. I am also using the combined "multiplication-assignment" operator to increase the end product.
Code: (Demo)
for ($i = 5, $product = 1; $i > 1; --$i) {
echo $i . ' x ';
$product *= $i;
}
echo $i . ' = ' . ($product * $i);
In a professional application, I'd probably use functional programming, but you are probably only doing this as an academic exercise. Regardless, here is one way that that style can look:
Code: (Demo)
$i = 5;
$range = range($i, 1);
printf(
'%s = %d',
implode(' x ', $range),
array_product($range)
);
This would do the trick:
$i = $num;
$factorial = 1;
$sep = "";
do {
echo "$sep $i";
$factorial = $factorial * $i;
$i--;
$sep = " x";
} while($i > 0);
echo (" = $factorial");
You can try this :
$i = $num;
$factorial = 1;
while($i > 0);
{
echo $i . ' x ';
//if($i>1) echo strrev(" x $i "); strrev would produce undesired output when $num is 10 or greater as pointed out by #wire
else echo $i;
$factorial = $factorial * $i;
$i--;
}
echo (" = $factorial");
Or use Ternary operator like :
$i = $num;
$factorial = 1;
while($i > 0){
echo( $i>1 ? $i . ' x ' : $i);
$factorial = $factorial * $i;
$i--;
}
echo (" = $factorial");
Conidering the input from #mickmackusa, I have modified my answer to fir the purpose.

display series of characters in a string using loops in php

I want to make a series, e.g, 1/2 + 3/4 + 5/6 + 7/8 + 9/10 + 11/12 as a string using loops in php. write now i have written this code:
$output='';
for ($i=0; $i < 6; $i++)
{
$output=$output.($i+1+$i).'/'.($i+2+$i);
if ($i==5)
{
break;
}
else
{
$output=$output.'+';
}
}
echo nl2br("\n4: $output");
output:
1/2 + 3/4 + 5/6 + 7/8 + 9/10 + 11/12
is there any other better approach to do that?
preg_replace('/(\d+) \+ (\d+)/', '$1/$2', implode(" + ", range(1, 12)));
https://www.ideone.com/dKUIwc
With minimum of code it is:
$output = [];
for ($i = 0; $i < 6; $i++) {
$output[] = (2 * $i + 1) . '/' . (2 * $i + 2);
}
echo implode(' + ', $output);
Start loop from 1 and make step of 2 instead of one. Then put every sequence to array and finally implode it with +
$output = [];
for ($i = 1; $i <= 12; $i += 2) {
$output[] = $i . '/' . ($i + 1);
}
echo implode(' + ', $output);
as a string using loops in php. --> display as a string...
Use for loop and modulus operator %. Display first key, a forward slash, then continue the iteration outside that conditional and display the next key, then display a plus sign.
Continue iteration until you evaluate if the value is at the end of the array. Two conditionals inside the loop.
I used a iterator defined as $i as using a foreach loop would start at zero and you would have to do some extra code to get the last value.
$myArray = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
$stmt = NULL;
for($i = 0; $i < count($myArray); $i++){
if($myArray[$i] % 2 ){
$stmt .= $myArray[$i]."/";
}else{
if($myArray[$i] !== end($myArray)){
$stmt .= $myArray[$i].' + ';
}else{
$stmt .= $myArray[$i];
}
}
}
OUTPUT:

Printing an equation from a 2D array using a for loop

$string = 3;
for ($i=0; $i<$string; $i++) {
for($j=0; $j<$string; $j++) {
print $arr[$i][$j] = rand(1,5);
}
print "<br>";
}
Basically this code will output something like
5 5 4
2 5 2
4 5 3
I want to print on the screen something like 5 + 5 + 4 + 2 + 5 + 2 + 4 + 5 + 3 = 35
I have tried multiple methods but am struggling when getting the + to print in the right places.
If I have understood you correctly then you can use the following code:
$arr = array();
$string = 3;
$temp = array();
$sum = 0;
for ($i=0; $i < $string; $i++) {
for($j=0; $j<$string; $j++) {
$arr[$i][$j] = rand(1,5);
$sum += $arr[$i][$j];
$temp[] = $arr[$i][$j];
}
}
echo implode(' + ', $temp).' = '.$sum;
Result:
2 + 5 + 3 + 3 + 4 + 2 + 5 + 3 + 1 = 28
EDIT (without the implode function [OP request in comments]):
$arr = array();
$string = 3;
$temp = '';
$sum = 0;
for ($i = 0; $i < $string; $i++) {
for($j = 0; $j < $string; $j++) {
$arr[$i][$j] = rand(1,5);
$sum += $arr[$i][$j];
if ($i == ($string - 1) && $j == ($string - 1)) {
$temp .= $arr[$i][$j];
} else {
$temp .= $arr[$i][$j].' + ';
}
}
}
echo $temp.' = '.$sum;
Result:
1 + 2 + 1 + 3 + 2 + 3 + 5 + 4 + 5 = 26

Calculate a specific number PHP

I have a for loop, where $i is 0, and it will run until $i reaches 4. I am trying to make a code that would output numbers in an order like this: 01, 11, 02, 12, 03, 13... etc... Now, the thing is next: when $i is 1, the script should make an order of those number in the boundaries of 1 and 20. When $i is 2, it would be 21 to 40, etc.
I've tried many things (mostly deleted), could not come up with anything that would work the right way.
The inner loop:
for ($j = 0; $j != 10; ++$j)
{
echo $j + 1 + 10 * ($i - 1);
echo $j + 1 + 10 * $i;
}
Try this piece of code;
<?php
$num = 4;
for($i=1;$i<($num + 1);$i++){
$string = "0" . $i . ", 1" . $i;
if($i<$num){
$string .= ", ";
}
echo $string;
}
?>
printf will format your numbers with a leading zero, as specified:
<?php
$format = "%02d ";
for ($i = 1; $i <= 4; $i++) {
$k = 2 * $i - 1;
for ($j = 1; $j <= 10; $j++) {
printf($format, ($k - 1) * 10 + $j);
printf($format, $k * 10 + $j);
}
echo "<br />";
}
?>
You can try:
<?php
$ten = 10;
for ($i = 0; $i<=4; ++$i)
{
echo "0".$i." , ";
echo $ten + $i."<br/>";
}
?>
Only change the range of $i
Thanks

php - for with 3 values

i have:
# = 1
# = 0,5
% = 0
max = 10
for example if i have: 3 then should show me:
###$$$$$$$
if i have 3,5 :
####$$$$$$
etc
if i have 3,99 then = 3,5
if i have 3,49 then = 3,0
etc
how can i use this with foreach or for?
for whole number i can make:
$number = 8;
$one = 10 - $number;
$three = 0 + $number;
and
for($i=1;$i <= $one){
echo "#";
}
for($i=1;$i <= $three){
echo "$";
}
but how is the best solution if $number = 3,57
If I've understood what you're after, this should do what you want:
<?php
function printItOut($number) {
$s = '';
for ($i = 0; $i < 10; $i++) {
if ($i < $number%10) {
$s .= '#';
} else if ($i < ($number+0.5)%10) {
$s .= '#';
} else {
$s .= '$';
}
}
return $s;
}
echo printItOut(3.49), "\n";
echo printItOut(3.5), "\n";
echo printItOut(3.99), "\n";
echo printItOut(4), "\n";
Outputs:
###$$$$$$$
####$$$$$$
####$$$$$$
####$$$$$$
Inside the for loop, I using the modulus operator to find the integer remainder of dividing $number by 10. So 3%10 gives a result of 3, 3.49%10 also results in 3.
In the first 'else if' block, I'm checking whether the number is 0.5 or more, since (3.49+0.5) is 3.99, and 3.99%10 is 3; but 3.5+0.5 is 4, and 4%10 is 4.

Categories