multiply each value that I get from 'for' statement in php - php

following is the steps in which i want to do things:
assign a value 1 to $x variable
using for loop increment this value upto 7, so that output is : 1234567
now multiply each value with 7, so that output is : 7 14 21 28 35 42 49.
for this i made the following code, but it does not work.
$yy=1;
for($yy==1; $yy<=8; $yy++){
$yy*7;
}echo $yy;
and i tried the do-while also :
$yy=1;
do{$yy*7;
echo $yy;}
while(
$yy>=7
)
but non is working. i think foreach will work here, not tried yet as i am not on it yet. will it be possible with any of these 2 functions?

You just need for loops:
for($yy = 1; $yy <= 7; $yy++){
echo $yy;
}
echo '<br/>';
for($yy = 1; $yy <= 7; $yy++){
echo $yy*7 .' ';
}
The result will be like this
1234567
7 14 21 28 35 42 49
You got wrong syntax: $yy==1 (comparison operator) on your for looop, initialize $yy=1 (assign operator) then the condition is $yy<=7 not eight

Related

Make an output of 1 2 4 8 11 12 14 18... using one for loop

How can I generate a sequence of numbers like
1 2 4 8 11 12 14 18 ...
(plus 10 every 4 numbers) with the following additional requirements:
using only one loop
output should stop when a value in the sequence is greater than a specified input
Examples
$input = 24;
1 2 4 8 11 12 14 18 21 22 24
$input = 20;
1 2 4 8 11 12 14 18
Here's what I tried so far:
<?php
// sample user input
$input = 20;
$number = 1;
$counter = 0;
$array = array();
//conditions
while ($counter < 4) {
$counter++;
array_push($array, $number);
$number += $number;
}
//outputs
for ($x = 0; $x < count($array); $x++) {
echo $array[$x];
echo " ";
}
Code: (Demo)
function arrayBuilder($max,$num=1){
$array=[];
for($i=0; ($val=($num<<$i%4)+10*floor($i/4))<=$max; ++$i){
$array[]=$val;
}
return $array;
}
echo implode(',',arrayBuilder(28)),"\n"; // 1,2,4,8,11,12,14,18,21,22,24,28
echo implode(',',arrayBuilder(28,2)),"\n"; // 2,4,8,16,12,14,18,26,22,24,28
echo implode(',',arrayBuilder(20)),"\n"; // 1,2,4,8,11,12,14,18
echo implode(',',arrayBuilder(24)),"\n"; // 1,2,4,8,11,12,14,18,21,22,24
This method is very similar to localheinz's answer, but uses a technique introduced to me by beetlejuice which is faster and php version safe. I only read localheinz's answer just before posting; this is a matter of nearly identical intellectual convergence. I am merely satisfying the brief with the best methods that I can think of.
How/Why does this work without a lookup array or if statements?
When you call arrayBuilder(), you must send a $max value (representing the highest possible value in the returned array) and optionally, you can nominate $num (the first number in the returned array) otherwise the default value is 1.
Inside arrayBuilder(), $array is declared as an empty array. This is important if the user's input value(s) do not permit a single iteration in the for loop. This line of code is essential for good coding practices to ensure that under no circumstances should a Notice/Warning/Error occur.
A for loop is the most complex loop in php (so says the manual), and its three expressions are the perfect way to package the techniques that I use.
The first expression $i=0; is something that php developers see all of the time. It is a one-time declaration of $i equalling 0 which only occurs before the first iteration.
The second expression is the only tricky/magical aspect of my entire code block. This expression is called before every iteration. I'll try to break it down: (parentheses are vital to this expression to avoid unintended results due to operator precedence
( open parenthesis to contain leftside of comparison operator
$val= declare $val for use inside loop on each iteration
($num<<$i%4) because of precedence this is the same as $num<<($i%4) meaning: "find the remainder of $i divided by 4 then use the bitwise "shift left" operator to "multiply $num by 2 for every "remainder". This is a very fast way of achieving the 4-number pattern of [don't double],[double once],[double twice],[double three times] to create: 1,2,4,8, 2,4,8,16, and so on. bitwise operators are always more efficient than arithmetic operators.The use of the arithmetic operator modulo ensure that the intended core number pattern repeats every four iterations.
+ add (not concatenation in case there is any confusion)
10*floor($i/4) round down $i divided by 4 then multiply by 10 so that the first four iterations get a bonus of 0, the next four get 10, the next four get 20, and so on.
) closing parenthesis to contain leftside of comparison operator
<=$max allow iteration until the $max value is exceeded.
++$i is pre-incrementing $i at the end of every iteration.
Complex solution using while loop:
$input = 33;
$result = [1]; // result array
$k = 0; // coeficient
$n = 1;
while ($n < $input) {
$size = count($result); // current array size
if ($size < 4) { // filling 1st 4 values (i.e. 1, 2, 4, 8)
$n += $n;
$result[] = $n;
}
if ($size % 4 == 0) { // determining each 4-values sequence
$multiplier = 10 * ++$k;
}
if ($size >= 4) {
$n = $multiplier + $result[$size - (4 * $k)];
if ($n >= $input) {
break;
}
$result[] = $n;
}
}
print_r($result);
The output:
Array
(
[0] => 1
[1] => 2
[2] => 4
[3] => 8
[4] => 11
[5] => 12
[6] => 14
[7] => 18
[8] => 21
[9] => 22
[10] => 24
[11] => 28
[12] => 31
[13] => 32
)
On closer inspection, each value in the sequence of values you desire can be calculated by adding the corresponding values of two sequences.
Sequence A
0 0 0 0 10 10 10 10 20 20 20 20
Sequence B
1 2 4 8 1 2 4 8 1 2 4 8
Total
1 2 4 8 11 12 14 18 21 22 24 28
Solution
Prerequisite
The index of the sequences start with 0. Alternatively, they could start with 1, but then we would have to deduct 1, so to keep things simple, we start with 0.
Sequence A
$a = 10 * floor($n / 4);
The function floor() accepts a numeric value, and will cut off the fraction.
Also see https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
Sequence B
$b = 2 ** ($n % 4);
The operator ** combines a base with the exponent and calculates the result of raising base to the power of exponent.
In PHP versions prior to PHP 5.6 you will have to resort to using pow(), see http://php.net/manual/en/function.pow.php.
The operator % combines two values and calculates the remainder of dividing the former by the latter.
Total
$value = $a + $b;
Putting it together
$input = 20;
// sequence a
$a = function ($n) {
return 10 * floor($n / 4);
};
// sequence b
$b = function ($n) {
return 2 ** ($n % 4);
};
// collect values in an array
$values = [];
// use a for loop, stop looping when value is greater than input
for ($n = 0; $input >= $value = $a($n) + $b($n) ; ++$n) {
$values[] = $value;
}
echo implode(' ', $values);
For reference, see:
http://php.net/manual/en/control-structures.for.php
http://php.net/manual/en/function.floor.php
http://php.net/manual/en/language.operators.arithmetic.php
http://php.net/manual/en/function.implode.php
For an example, see:
https://3v4l.org/pp9Ci

For-loop mystery in PHP

Using PHP 5.6, why does this code outputs
2
5
8
11
instead of
3
6
9
?
for ($i = 0; $i < 10; $i++) {
echo $i += 2 . "<br />";
}
Because i starts at 0, not 1. Lets see what is happening:
Loop 1
Initiate i, i = 0;
Check for loop condition ($i < 10). i is 0 so yes, run the loop.
Add 2 to i and echo. 0 + 2 = 2, echo 2.
End of loop, add 1 to i. i is 3.
Loop 2
Check for loop condition ($i < 10). i is 3 so yes, run the loop.
Add 2 to i and echo. 3 + 2 = 5, echo 5.
End of loop, add 1 to i. i is 6.
And so on. So you add 2, echo out then add 1.
You may be expecting the i++ in the for loop to run before the code, but it runs at the end of the code. From the PHP website:
At the end of each iteration, expr3 is evaluated (executed).
If you want your output to be 3, 6, 9 then you would need to initiate i to 1 at the start of your loop.
for($i = 1; $i < 10; $i++)
The increment (i++) in the loop header happens after the loop body is executed. So, i is initialized to 0, then you add 2 and print it. Then, the loop header increments it to 3, then you add 2 and print it again...
In the first iteration, you add 0 + 2, because you declared $i to be 0, so the output would be 2. then with the $i++ you do the same as you would write $i += 1. So now the value of $i is 3.
Then you add again 2 which gives you 5 as an output, then you add another 1. Value of $i = 6, add 2... outputs 8... add 1... add 2... outputs 11...

My script does not working correctly it starts and not stop after it

I am working on a function, but that function is not working properly when
I run it, then it runs continuously.
I didn't find where is actual problem is.
<?php
function recursion($a) {
if($a < 20) {
echo "$a\n";
recursion($a);
}
}
$a = 2;
recursion($a);
echo "</br>";
?>
Your recursion function going to infinite because you are passing same value again and again with recursion($a); so if($a<20) will be always result true and recursion won't break ever.
Try increment ++$a or $a += 1 or $a = $a+1.
recursion(++$a);//increasing value with prefix operator ++
Complete code:
function recursion($a) {
if($a < 20) {
echo "$a\n";
recursion(++$a);
}
}
$a = 2;
recursion($a);
echo "</br>";
Output:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

PHP column to line in arrays

I have come to this part of script so far:
dif($result>0)
{
$ii=0;
$jj=0;
while (odbc_fetch_row($result))
{
for ($jj = 1; $jj <= odbc_num_fields($result); $jj++)
{
$rr[$ii][$jj]=odbc_result($result,$jj);
if(is_null($rr[$ii][$jj]))
$rr[$ii][$jj] = noData;
echo $rr[$ii][$jj];
echo "<br />";
}
$ii++;
}
}
This works good for creating and populating dynamic tables. But i need also to create dynamic number of single line arrays which consist of column values of arrays i get previously.
Example:
if i get
Array1
2012.01.01 10 20 30
2012.01.02 1 2 3
2012.01.03 11 22 33
i need to convert to
Array2
2012.01.01 2012.01.02 2012.01.03
Array3
10 1 11
Array4
20 2 22
Array5
30 3 33
As i mentioned before the first part of script is needed, so is there a possibility to use result to create single line arrays for further use? I suppose i'm missing something...
What is wrong with a for loop and adding the elements to an array?'
$rr = array(array(1,2,3,4,5),array(6,7,8,9,0),array(11,22,33,44,55));
$result = array();
for($j=0;$j<count($rr[0]);$j++){
$col = array();
for($i=0;$i<count($rr);$i++) {
array_push($col,$rr[$i][$j]);
}
array_push($result,$col);
}
print_r($result);
for a demo see this codepad: http://codepad.org/wgSCtoMV

PHP For Loop Confusion

Am new to the world of coding and it is my first time understanding loops. I saw an example at a website and am utterly confused by the result.
/* Sample Code 1 */
$counter=0
$start=1
for($start;$start<11;start++) {
$counter=$counter+1;
print $counter;
}
This gives me the result of 1,2,3,4,5,6,7,8,9,10
Now if I update the code as follows
/* Sample Code 2 */
$counter=11;
$start=1;
for($start;$start<11;start++) {
$counter=$counter+1;
print $counter;
}
This gives me the result 12,13,14,15,16,17,18,19,20
However if I update the code as follows
/* Sample Code 3 */
$counter=11;
$start=1;
for($start;$start<11;start++) {
$counter=$counter-1;
print $counter;
}
I get the result 10,9,8.7.6,5,4,3,2,1
Please correct me if I am wrong
If the variable $counter has the value of 11, I am essentially start the increment at 11+1 in the code $counter=$counter+1. Is that correct?
But what confuses me is that how is the result in Sample Code 2 possible if my end value in the FOR loop is $start<11. Doesn't this mean it has to be less than 11?
When you start the loop, $start is less than 11. Then it is incremented at the end of the iteration. Then, the loop ends if it has reached 11.
That is, if $start is 10, then it will enter the loop. It reaches 11, so the for statement exits the loop. It is 11 when the loop ends.
Here is a description i wrote
for (//declare loop
$start = 0; //declare starting value and the value to store it in
$start < 10; // Each time it comes through, if $start is under 10, do the loop. if it is 10, exit
$start++ //Increment $start by 1
)
it seems that you're missing "21" in your second example results.
Could this be the cause of your confusion?
I'll give you an explanation from all example above:
Sample Code 1
$counter=0;
$start=1;
This is variable declaration to declare and initialize both variable.
for($start;$start<11;start++) {
$counter=$counter+1;
for loop has structure:
for({loop initialization}; {loop condition}; {per loop process}){
//the rest of loop process
}
Explanation:
As you can see, example #1 start loop from 1 (taken from $start = 1) and doing loop for as long as $start is smaller than 11. To prevent it from looping forever, that code add $start++ which translate to $start = $start + 1. This way, for every loop, $start is added by 1.
the loop condition has to return true in order the loop to run. If it return false, loop will quit.
Now, let's examine what's inside that loop:
$counter=$counter+1;
print $counter;
You see there: $counter=$counter+1. It means, you increment $counter by one for every loop and print the resulting $counter.
Let's breakdown the process (we start loop # with 1 as it's what's defined by $start = 1):
loop # $start ($start < 11?) $counter ($counter = $counter + 1)
1 1 Y 1
2 2 Y 2
3 3 Y 3
4 4 Y 4
5 5 Y 5
6 6 Y 6
7 7 Y 7
8 8 Y 8
9 9 Y 9
10 10 Y 10
11 11 N 11
From process breakdown above, we can see that condition ($start < 11) is result in false on loop #11. That's why the result is 1..10, not 1..11.
Same goes with Example #2:
$counter=11;
$start=1;
Loop structure:
for($start;$start<11;start++) {
$counter=$counter+1;
Let's breakdown this process:
loop # $start ($start < 11?) $counter ($counter = $counter + 1)
1 1 Y 12
2 2 Y 13
3 3 Y 14
4 4 Y 15
5 5 Y 16
6 6 Y 17
7 7 Y 18
8 8 Y 19
9 9 Y 20
10 10 Y 21
11 11 N 22
This will output 12..21. Because when loop #11 occured, it check that $start < 11 is false. Therefore, loop quit.
Please analyze your code.. you have a clear confusion b/w $start and $ counter variable. please use var_dump so as to see what your variables are going through

Categories