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

$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

Related

PHP Simple Calculation with an Array

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

How to arrange PHP for loop value?

This is my example of seat list arrangements. I have to show some seat alignment changes.
$rows=($data['seat_type']==1)?3:4;
$cols=round($numofseats /$rows) ;
$rowCssPrefix= 'row-';
$colCssPrefix= 'col-';
$seatWidth= 35;
$seatHeight= 35;
$seatCss= 'seat';
$selectedSeatCss= 'selectedSeat';
$selectingSeatCss= 'selectingSeat';
$window_rows = ($data['seat_type']==1) ? array(0,2) :array(0,3);
for ($i = 0; $i < $rows; $i++) {
$seat_w=(in_array($i,$window_rows))?'W':'A';
for ($j = 0; $j < $cols; $j++) {
$seatNo = ($i + $j * $rows + 1);
if($seatNo <= $numofseats)
{
$className = $seatCss . ' '.$rowCssPrefix .$i.' '.$colCssPrefix .$j; if($j % $cols==0) echo '<br>';
if(!in_array($seatNo,$booked_seats)) {
echo'<li class="' . $className.'" style="top:'. ($i *$seatHeight).'px;left:'. ($j *$seatWidth).'px" title="'.$seatNo.$seat_w.'">'.$seatNo.'<input type="checkbox" name="seat[]" value="'.$seatNo.'-'.$seat_w.'"/></li>';
}else{
$className .= ' '.$selectedSeatCss;
echo'<li class="' . $className.'" style="top:'. ($i *$seatHeight).'px;left:'. ($j *$seatWidth).'px">'.$seatNo.'</li>';
}
}
}
}
So I am getting the result like
1 4 7 10
2 5 8 11
3 6 9 12
but it should be
1 6 7 12
2 5 8 11
3 4 9 10
How can I get like this?
Thanks
You should reverse your seat number calculation if you're calculating a number for an odd column.
Change the calculation line to :
$seatNo = (($j % 2) > 0) ? (($rows - $i) + ($j * $rows)) : ($i + $j * $rows + 1);
What's happening here is, we are controlling if the column is odd or even by ($j % 2) > 0; then calculating the number accordingly.
So your code should look like this :
<?php
$rows=($data['seat_type']==1)?3:4;
$cols=round($numofseats /$rows) ;
$rowCssPrefix= 'row-';
$colCssPrefix= 'col-';
$seatWidth= 35;
$seatHeight= 35;
$seatCss= 'seat';
$selectedSeatCss= 'selectedSeat';
$selectingSeatCss= 'selectingSeat';
$window_rows = ($data['seat_type']==1) ? array(0,2) :array(0,3);
for ($i = 0; $i < $rows; $i++) {
$seat_w=(in_array($i,$window_rows))?'W':'A';
for ($j = 0; $j < $cols; $j++) {
// If we are on the first (or 3rd, 5th, odd numbers) column, normally continue numbering,
// But if we are on an even column, reverse the numbering by (($rows - $i) + ($j * $rows)).
$seatNo = (($j % 2) > 0) ? (($rows - $i) + ($j * $rows)) : ($i + $j * $rows + 1);
if($seatNo <= $numofseats)
{
$className = $seatCss . ' '.$rowCssPrefix .$i.' '.$colCssPrefix .$j; if($j % $cols==0) echo '<br>';
if(!in_array($seatNo,$booked_seats)) {
echo'<li class="' . $className.'" style="top:'. ($i *$seatHeight).'px;left:'. ($j *$seatWidth).'px" title="'.$seatNo.$seat_w.'">'.$seatNo.'<input type="checkbox" name="seat[]" value="'.$seatNo.'-'.$seat_w.'"/></li>';
}
else {
$className .= ' '.$selectedSeatCss;
echo'<li class="' . $className.'" style="top:'. ($i *$seatHeight).'px;left:'. ($j *$seatWidth).'px">'.$seatNo.'</li>';
}
}
}
}
?>
The relevant line I assume is
for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j < $cols; $j++) {
$seatNo = ($i + $j * $rows + 1);
}
}
In order to get an "reverse effect", simply add an if condition to each odd column.
for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j < $cols; $j++) {
if ($j % 2 == 1) $seatNo = (($rows - $i) + $j * $rows );
else $seatNo = ($i + $j * $rows + 1);
}
}

continously loop with adding different value

I'm new in PHP. How can i achieve continously loop with adding different value?
it's something like this
<?php
$gap1 = 2;
$gap2 = 3;
$lenght = 10;
for( $i=0; $i<$length; $i++ )
{
//the code
}
?>
and the result will be : 0 2 5 7 10 12 15 17
thank you for your help :)
$gap1=2;
$gap2=3;
$lenght = 10;
$p=0;
for($i=0;$i<$lenght;$i++)
{
if($i==0){$p=0;}
elseif($i%2==0)
{
$p+=$gap2;
}
else{
$p+=$gap1;
}
echo $p.'<br>';
}
Try this code:
$gap1 = 2;
$gap2 = 3;
$length = 10;$i=0;
$x = 0;
while($i<$length)
{
echo $x." ";
if($i%2 == 0)
$x+=$gap1;
else
$x+=$gap2;
$i++;
}
Output:
0 2 5 7 10 12 15 17 20 22
$gap = array(2, 3);
$result = array(-1 => 0);
$length = 10;
for($i = 0; $i < $length; $i++) {
$result[] = $result[$i-1] + $gap[($i) % count($gap)];
}
echo implode(' ', $result);

Why does $m = 40?

Why does $m = 40 on this? I am new in php and I get why $k = 40 , but I cant figure out why $m = 40 as well.
<?php
$i = 29;
$j = 11;
$m = 10;
$k = $i++ + $j--;
echo "k = ".$k."<br>";
$j = ($j - 4) / 2;
$m += $j * 10;
echo "m = ".$m."<br>";
?>
<?php
$i = 29;
$j = 11;
$m = 10;
$k = $i++ + $j--;
// $j == 10
echo "k = ".$k."<br>";
$j = ($j - 4) / 2;
// $j = (10 - 4 ) / 2 == 3
// $m == 10
$m += $j * 10;
// $m + $j * 10 = 10 + 3 * 10 == 40
echo "m = ".$m."<br>";
?>
fast explaination of what's happening:
$k = 29 + 11 = 40;
$i = 30 (++)
$j = 10 (--)
echo K = 40
$j = (10-4) / 2 = 3
$m = 3 * 10 + 10 = 40
the '+=' operator add the results of the operation on the right ($j * 10) to the value on the left ($m that contains 10)
Here it is:
$i = 29;
$j = 11;
$m = 10;
$k = $i++ + $j--;
// $k = 40
// $i = 30
// $j = 10
echo "k = ".$k."<br>";
//echo k = 30
$j = ($j - 4) / 2;
// $j = 3
$m += $j * 10;
// $m = 10 + ( 3 * 10 ) = 40
echo "m = ".$m."<br>";
//echo m = 40
It's probably the $++ and ++$ the puzzles you.
// First try:
$a = 0;
$b = 1;
var_dump($c = $a + $b++); // means: $c = $a + $b; $b = $b + 1;
// Second try:
$a = 0;
$b = 1;
var_dump($c = $a + ++$b); // means: $b = $b + 1; $c = $a + $b;
^ make sense?
$j = ($j - 4) / 2; // $j is equal with 10 because of decrement $j-- before
$m += $j * 10; // after that line, $j becomes (10-4)/2 which is 3
echo "m = ".$m."<br>"; // and finally $m = $m + ($j * 10) => 10 + (3 * 10)

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

Categories