For loop inside a function PHP - php

A total noob needs to do a math calculation in a for loop inside a function.
The closest I come is this, but it does not work of course.
function z1()
{
for ($x=1; $x<=11; $x++)
{
$z1=2/3+5*$x/(3-$x);
}
return $z1;
}
Any help or a solution would be appreciated
EDIT: FIXED
Needed to declare what to do if it is NaN or infinite

Not entirely sure what you're trying to do, but I'll make some assumptions.
In addition to a divide by zero error this gets, you are overwriting the value of $z1 each time the loop executes, so the value of $z1 once you return is whatever the final iteration of the loop assigned to $z1.
I think you may want to initialize the variable before the loop and use the += operator inside the loop, so the value of $z1 is incremented each time the loop iterates.
function z1() {
$z1 = 0;
for ($x = 1; $x <= 11; $x++) {
$z1 += 2 / 3 + 5 * $x / (3 - $x);
}
return $z1;
}

Related

How does for loop works actually in php?

I'm a newbie to php and I've understood all other loops in php but the question is I cannot understand how the for loops works for ex:
Here is the code;
$a = 0;
$b = 0;
for ($i=0; $i < 5; $i++) {
$a += 10;
$b += 5;
}
echo("At the end of the loop a=$a and b=$b");
When I execute this script the value of a = 50 and b = 25!
Is it multiplying the a value with i's increment value? like 10 * 5 = 50.
You start with $i=0, then you do $a+10 and $b+5 as long as $i <5
$i=0, $a=10, $b=5
$i=1, $a=20, $b=10
$i=2, $a=30, $b=15
$i=3, $a=40, $b=20
$i=4, $a=50, $b=25
$i=5, now the loop stops because $i is no longer <5
Your loop runs five times. Each time through the loop you add 10 to the value of $a. Doing that five times gives you 50.
This is the way it works.
Let's say you have a no dollars. And I tell you that I will give you a dollar everytime you do 5 chores. However, I will only give you 5 dollars. At first you have no dollars and after one chore I give you 5 dollars. Now you have 5 dollars. You do another chore and I give you another 5, bringing you to ten. I have now given you two dollars. I give you another 5 - you have 15. I give you another - 20 - and one more; bringing you to 25 dollars. Now I have given you my limit of dollars, and our loop is complete.
In this story, my dollars are your $i value. Beginning at 0, working up to 5. Your chores are your $b values, which are added to every time.
Code example:
for ($dollars=0; $dollars < 5; $dollars++) {
$chores += 5;
}
+= is not increment its an assignment operator.
http://php.net/manual/en/language.operators.assignment.php
As I mentioned in the comments, and others in their answers. += will add the value to on the right to the value on the left. so in a loop its like this
step 0 $a = 5 ( 0+5)
step 1 $a = 10 (5[previous iteration exit value]+5 )
step 2 $a = 15 (10[previous iteration exit value] + 5)
so on....
Of note is you can also do -= *= etc. and .=or append all the same kind of operation.
The for statement is used when you know how many times you want to execute a statement or a block of statements.
Syntax:
for (initialization; condition; increment){
code to be executed;
}
The initializer is used to set the start value for the counter of the number of loop iterations. A variable may be declared here for this purpose and it is traditional to name it $i.
Example
The following example makes five iterations and changes the assigned value of two variables on each pass of the loop −
<html>
<body>
<?php
$a = 0;
$b = 0;
for( $i = 0; $i<5; $i++ ) {
$a += 10;
$b += 5;
}
echo ("At the end of the loop a = $a and b = $b" );
?>
</body>
</html>
This will produce the following result −
At the end of the loop a = 50 and b = 25
For loop is entry condition loop. It evaluate condition first, so the statement block associated with the loop won't run even once if the condition fails to meet
The statements inside this for loop block will run 5 times, the value of $i will be 0 to 4;
Imagine the loops are running separately.
$a=0;
$b=0;
for ($i = 0; $i < 5; $i++){
echo $a += 10;
echo '<br>';
}
And the output like this.
10
20
30
40
50
Now another Loop
for ($i=0; $i < 5; $i++) {
echo $b += 5;
echo '<br>';
}
And the output like this
5
10
15
20
25
In each iteration it adds 10 and 5 to previous number of iteration using the assignment operator x += y.

do while loop converting temperature php not looping

Hi this is a table converting celsius to kelvin and fahrenheit, I am just wondering why my code does not loop :( it only displays the first two lines and stops. Thank you!
<?php
$celsius = 100;
$stop_kelvin = 0;
print '<table>';
print '<tr><th>Degrees Celsius(C)</th><th>Kelvin(K)</th><th>Degrees Fahrenheit(F)</th></tr>';
while ($kelvin <= $stop_kelvin) {
$fahr = ($celsius*1.8) + 32;
$kelvin = $celsius + 273;
print"<tr><td>$celsius</td><td>$kelvin</td><td>$fahr</td></tr>";
$fahr += 1;
}
print '</table>';
?>
In your code, $kelvin variable is not initialized. Also, please re-think your loop logic.
First of all you havent initialized $kelvin; because of which $kelvin is taking some random values.
After first loop the value of $kelvin becomes 373 and in your loop it is $kelvin <= $stop_kelvin means the condition is false and it jumps out of the loop

Add up numbers in a for each PHP?

I'm trying to add some numbers in a foreach loop in my PHP code. I am getting a percentage of numbers in a while loop in my MySQL query for each result that I get in my PHP page.
All I need to do is to add up the final values in and show them as total.
This is how I make up the percentage in my while loop in my MySQL query:
$percentage = 10;
$totalWidth = $fees;
$new_width = ($percentage / 100) * $totalWidth;
The $fees value is dynamic and it is different for each result in my while loop. the code above works as it should.
Now I want to add up all the values of $new_width. For example:
If one result's $new_width is 25 and the other one is 10 and another one is 5, I need to do this: $total = 25 + 10 + 5;
So I tried something like this:
$total = 0;
foreach($new_width as $var) {
$total = $var + $var;
}
echo $total;
but the above code doesn't really make sense and it won't do anything at all.
Could someone please advise on this matter?
First you want to change this line in your while loop so you get an array:
$new_width = ($percentage / 100) * $totalWidth;
to this:
//Declare it as an array before your while loop
$new_width = array();
//In your while loop
$new_width[] = ($percentage / 100) * $totalWidth;
//^^ See here
After this you just have to change the line in your foreach loop like this:
$total = $var + $var;
to this:
$total += $var;
(If you want you also can do this in your while loop)
If you have an array of numbers and you want to calculate the sum of those numbers, you should use array_sum().
According to the logic, you are setting the total to 2 X $var.
My answer is very similar, but you add it to the total which is outside of the loop and the value will keep growing:
$total = 0;
foreach($new_width as $var) {
$total += $var;
}
echo $total;
Or simply as stated before, if it is the only value in the array:
$total = array_sum($new_width);

PHP - Repeat and append a variable to a calculation

I am trying to create a script that takes a $$variable and adds them to each other a number of times (based on another variable) - $total
This script is part of a much larger script that contains a few SQL queries and loops, hence the $$value as opposed to the usual $value
My current (static) script is like so:
$$value = ($$value + $$value + $$value + $$value + $$value);
This will work if I continue to modify the number of + $$value within the brackets but I need it to auto calculate and ammend itself so that it always writes the correct number of + $$value
I have tried using str_repeat() but it only fetches the first value of the $$value variable and then repeats that value (not grabbing the next value and so on). I have also tried creating a loop, which also didn't work.
I need something that will look at $total and from that number produce something similar to the following:
$$value = ($$value * $total)
The above will multiply the numeric value of the $$value and therefore not return the result I want.
Can anyone help?
Many thanks,
Tom
Pastebin Link to my script: http://pastebin.com/7Qg02hWB (in the pastebin, $$value is $$ob_id and $total is $o_total)
Not 100% sure what you mean, but how's
$foo = "";
for ($i = 0; $i < $total; $i++) $foo .= $$value;
$$value = $foo;
This will loop over $total times and concatenate it. If you're having problems like it's adding it as an integer for some reason you could always do a cast like (string) $$value. I know you said you tried a loop but we have no code so it could have been a problem with your code.
this?
perhaps you need powers?
$total = 5;
$$variable = 2; // random value; and why i have two 2 $$ ?
for($x=0;$x<$total;$x++) {
$$variable += $$variable;
}
echo $$variable;
OR,
$total = 5;
$$variable = 2;
echo "<br>POWER of 2^$total: ".pow($$variable,$total);

How to increase number of iterations from within the loop in php?

I'm working on custom pagination system and encountered following problem. When one of the elements is filtered out of the set, the size of the final array is smaller than needed. Therefore I'm looking for a solution to increase the number of iterations from within the loop to always get array consisting of 50 elements.
$limit = 50; //Number of elements I want to fetch
for($x=0; $x<$limit; $x++){
if ($elementIsNotFiltered) {
//add element to $someArray;
}
else {
//increase the number of iterations, so even if some elements are filtered out,
//the size of $someArray will always be 50
}
}
Thanks for any help.
Do it in a while() loop instead, and break when you finally hit your $limit
Use a while loop.
while(count($somearray) < 50 && /*elements remain*/) ...
else {
++$limit;
}
Tried that?
You may also do the same thing the other way round:
else {
--$x;
}
Or be a little bit more effective:
$x = 0;
while ($x != 50) {
if ($notFiltered) {
++$x;
}
}
If you want to save the counter variable, too, you may use:
while (!isset($array[49])) {
}
The !isset($array[49]) here is only a synonym of count($array) < 50.
It sounds to me like you're looking for a while loop - not a for loop:
while ($items < 50 && [more items to filter]) {
if ([add to array]) {
$items++;
}
}
If you really want to do it in your for loop you can always modify $x but this makes your code unreadable and hard to maintain - I would recommend not doing this...

Categories