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:
Related
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.
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
I have an array of numbers in the codes shown below.
$result_data = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
$arrayCount = count($result_data);
for ($x = 0; $x < $arrayCount; $x++)
{
if ($x%5==0)
{
$sum = $result_data[0] + $result_data[1] + $result_data[2] + $result_data[3] + $result_data[4];
echo json_encode($sum);
echo ("\n");
}
}
And I got the result of:
15 15 15 15
Actually I wanted the results to be the sum of every 5 numbers in the array continuously and would expect the result to be:
15 40 65 90
Anyone knows how to get this?
You could reduce all of that code to:
$result_data = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
echo implode('\n', array_map('array_sum', array_chunk($result_data, 5))),'\n';
Which outputs:
15
40
65
90
See the man pages for:
array_chunk
array_map
array_sum
implode
Instead of referecing $result_data[1], $result_data[2], $result_data[3] etc you need to base the ID off your current $x value, like this
$sum = $result_data[$x] + $result_data[$x+1] + $result_data[$x+2] + $result_data[$x+3] + $result_data[$x+4]
A different approach
I would probably approach this in a different manner, continuously adding the values as I went along, and outputting the current total when I got to each fifth number, something like this:
$result_data = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
$arrayCount = count($result_data);
$subtotal = 0;
for ($x = 0; $x < $arrayCount; $x++)
{
$subtotal += $result_data[$x];
if ($x%5==0)
{
echo json_encode($subtotal);
echo ("\n");
$subtotal = 0;.
}
}
try this:
$result_data = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
$arrayCount = count($result_data);
for ($x = 0; $x < $arrayCount; $x++)
{
if ($x%5==0)
{
$sum = $result_data[$x] + $result_data[$x+1] + $result_data[$x+2] + $result_data[$x+3] + $result_data[$x+4];
echo json_encode($sum);
echo ("\n");
}
}
Instead of
$sum = $result_data[0] + $result_data[1] + $result_data[2] + $result_data[3] + $result_data[4]
you probably wanted
$sum = $result_data[$x] + $result_data[$x+1] + $result_data[$x+2] + $result_data[$x+3] + $result_data[$x+4]
You can use:
$sum = $result_data[$x] + $result_data[$x+1] + $result_data[$x+2] + $result_data[$x+3] + $result_data[$x+4]
instead of:
$sum = $result_data[0] + $result_data[1] + $result_data[2] + $result_data[3] + $result_data[4];
since you've assigned $x inside your for loop.
Demo
Working demo
$result_data = range(1,20);
foreach($result_data as $key=>$value){
if($value%5==0){
echo $value+$result_data[$key-1]+$result_data[$key-2]
+$result_data[$key-3]+$result_data[$key-4]."\n";
}
}
Output :
15
40
65
90
I'm trying to echo stars and zero like the pattern below
*
***0
******00
**********000
The length of the asterisks grows by an increasing factor (in a ballooning fashion) -- the previous number of asterisks plus the current iteration number.
iteration 1: 1 (0 + 1)
iteration 2: 3 (1 + 2)
iteration 3: 6 (3 + 3)
iteration 4: 10 (6 + 4)
iteration 5: 15 (10 + 5)
etc
The length of the zeros increases by a static factor.
iteration 1: 0
iteration 2: 1
iteration 3: 2
iteration 4: 3
iteration 5: 4
etc
My code currently looks like this:
for ($i=0; $i<=10; $i++)
{
echo "*";
for ($j=0; $j<$i; $j++)
{
echo "*";
}
for ($z=0; $z<$i; $z++)
{
echo "0";
}
echo "</br>";
}
However I'm getting this result:
*
**0
***00
****000
*****0000
******00000
The number of stars is indicated by triangle numbers, 1, 1+2, 1+2+3. You want to increment your inner loop max value by $i with every iteration:
$k = 0;
for ($i=1; $i<=10; $i++)
{
$k += $i;
for ($j=1; $j<=$k; $j++)
{
echo "*";
}
...
}
This is also a good case where your loops should be initialized with 1 rather than 0, because it is more intuitive. 0-based loops work best when you are working with arrays.
I think something like this is more efficient; you can cache the current sequence of stars and zeros.
$cache_star = "";
$cache_zero = "";
for ($i=1; $i<=10; $i++)
{
for ($j=1; $j<=$i; $j++)
{
$cache_star .= "*";
}
echo $cache_star.$cache_zero;
$cache_zero .= "0";
}
Here's what I got:
for($i = 1; $i != 5; $i++)
{
$triangle = (0.5 * $i) * ($i + 1);
echo str_repeat('*', $triangle) . str_repeat('0', $i) . PHP_EOL;
}
Uses the formula 0.5n(n + 1) - the triangle numbers formula.
Example output:
*0
***00
******000
**********0000
I quite like #jordandoyle's approach, but I correct the zeros pattern by subtracting 1 from $i in the second str_replace()..
Code: (Demo)
$number = 5;
for ($i = 1; $i <= $number; ++$i) {
echo str_repeat('*', $i * .5 * ($i + 1))
. str_repeat('0', $i - 1)
. PHP_EOL;
}
Output:
*
***0
******00
**********000
***************0000
If this answer lacks significant uniqueness versus an earlier answer, I'll include a recursive approach as well (instead of a classic loop).
Code: (Demo)
function printLines($i, $lines = [], $newline = PHP_EOL) {
if ($i > 0) {
array_unshift(
$lines,
str_repeat('*', $i * .5 * ($i + 1))
. str_repeat('0', $i - 1)
);
printLines(--$i, $lines);
} else {
echo implode($newline, $lines);
}
}
printLines(5);
You can even copy the previous line and insert it into the middle of the next line to form the desired pattern. This is the functional-style equivalent of #CoertMetz's nested loop technique.
Code: (Demo)
$number = 5;
$line = '';
for ($i = 1; $i <= $number; ++$i) {
echo (
$line = str_repeat('*', $i)
. $line
. ($i > 1 ? '0' : '')
)
. PHP_EOL;
}
All above techniques deliver the same result.
Smells like homework... But ok, what about this:
$star = "*";
echo $star."\n";
for ($i=0; $i<=10; $i++)
{
$star = $star."**";
echo $star;
echo str_repeat("0", $i+1);
echo "\n";
}
Outcome:
*
***0
*****00
*******000
*********0000
***********00000
*************000000
***************0000000
*****************00000000
*******************000000000
*********************0000000000
***********************00000000000
Demo:
http://sandbox.onlinephpfunctions.com/code/583644f782005adb9e018b965cbbdefaf63c7c79
Given this PHP for loop
$row->frequency = 1;
$row->date_1 = 10000;
$row->interval = 86400;
for ($i = 0; $i <= $row->frequency; $i++) {
$cal_data[] = array(
'start' => strtotime($row->date_1) + $row->interval,
);
}
I would like the first iteration of the loop to ignore the + $row->interval giving me as a result:
10000
96400
I've seen this done with modulus but couldn't manage to make it work here. Anyone have suggestions?
Thanks!
Use + ($i ? $row->interval : 0)
In other words, if $i is zero - first iteration - add 0 instead of $row->interval. This is the ternary operator, (condition ? iftrue : iffalse) which is roughly equivalent to an if/else construction except it can be used amidst a statement.
for ($i = 0; $i <= $row->frequency; $i++) {
if ($i == 0) {
$val = strtotime($row->date_1) ;
} else {
$val = strtotime($row->date_1) + $row->interval;
}
$cal_data[] = array(
'start' => $val
);
}