I read this Manual by PHP.com about While loops.
I don't understand the purpose of While loops in PHP.
It looks exactly like an if statement to me.
What is the difference between an if statement and a while loop?
How do while loops work, what do they do, and when should I use them?
For example, can't this:
$i = 1;
while ($i <= 10) {
echo $i++;
}
be done like this?:
$i = 1;
if ($i <= 10) {
echo $i++;
}
An if statement checks if an expression is true or false, and then runs the code inside the statement only if it is true. The code inside the loop is only run once...
if (x > y)
{
// this will only happen once
}
A while statement is a loop. Basically, it continues to execute the code in the while statement for however long the expression is true.
while (x > y)
{
// this will keep happening until the condition is false.
}
When to use a while loop:
While loops are best used when you don't know exactly how many times you may have to loop through a condition - if you know exactly how many times you want to test a condition (e.g. 10), then you'd use a for loop instead.
A while loop will run as many times as it needs to while a condition is true, i.e., until that condition is false.
An if statement will execute once if a condition is true.
A great way to understand concepts like this when you're just learning a language is to try them out:
<?php
$i = 1;
while ($i <= 10) {
echo $i++;
}
echo "\n";
$i = 1;
if ($i <= 10) {
echo $i++;
}
This results in:
12345678910
1
if command is only run in one condition in one time and its execute in only one statement in one time
while loop is manly use in infinite time for looping a statement while is executed in many statement in one time
Here's an example:
Suppose you want a script that loops through an array and make one beep sound for each element of the array.
A WHILE loop would generate no beeps for an empty array.
An FOR loop will always run at least once, so an empty array would generate one beep.
Related
I am new in PHP. I know a little bit about how for loops work. Using this format: (initial; conditions; increment) why doesn't this loop work? What kind of conditions are allowed?
Here is the code:
<?php
$name = "Biswajit";
for ($i = 1; $name[$i] == "w"; $i++) {
echo "hello";
}
?>
The condition can be any expression whatsoever that can be usefully evaluated to true or false.
The condition is tested once at the start of each iteration of the loop. The loop ends as soon as one of these tests gives false.
Your example condition $name[$i] == "w" is syntactically valid, but will end the loop immediately, because $name[1] is i, not w. (Note that string characters start from 0.) Maybe you meant to write $name[$i] != "w".
So a for loop in PHP is pretty much like any other for loop in any other language.
Basically, you'll be able to put in condition that results to a boolean (notably ==, >, <, >=, <=).
Here's a basic example of a for loop in PHP printing a number:
for($i = 0; $i < 5; $i++) {
echo $i;
}
Hope this simple example can help! :)
trying to use a do while loop but it never finishes. Can't figure out why
<?php
$a = "2018-11-28T14:36:27+00:00";
$b = "2018-11-28T14:43:27+00:00.";
if ($a !== $b) {
echo "not equal";
}
else {
echo "equal";
}
do {
echo "a";
} while ($a !== $b);
do while statement :
"The expression in a do-while statement is evaluated after the body of the loop is executed. Therefore, the body of the loop is always executed at least once."
additionnal explaination from php manual
"do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning. The main difference from regular while loops is that the first iteration of a do-while loop is guaranteed to run (the truth expression is only checked at the end of the iteration), whereas it may not necessarily run with a regular while loop (the truth expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the beginning, the loop execution would end immediately). "
because do while body is exectued at least one time it will echo "a" but your condition is always true and you don't change your values into do while body; then you will get an infinite loop
I have a for loop like
for ($x=1; $x<=5; $x++){
($x == 3)? continue : true;
//some code here
}
now on execution I am getting error
PHP Parse error: syntax error, unexpected 'continue' (T_CONTINUE) in
/var/www/html/all.php on line 21
Now, this leave me with 2 questions:
Can I use continue key word inside short if statement?
For the else part of the short if, can binary values like true or false be used, and if not then how can I use short if statement if I have nothing to do for the else part.
continue is a statement (like for, or if) and must appear standalone. It cannot be used as part of an expression. Partly because continue doesn't return a value, but in an expression every sub-expression must result in some value so the overall expression results in a value. That's the difference between a statement and an expression.
cond ? a : b means use value a if cond is true else use value b. If a is continue, there's no value there.
true does result in a value (true), so yes, it can be used as part of an expression.
You cannot use continue inside short if-statement. Short if-statements is for returning values, like this
$val = $bool ? $one : $two;
Now, $val will have either the value of $one or the value of $two, depending of the truth value of $bool.
continue is no value, so it cannot be used in short if-statement. Use normal if-statement for this operation.
In this case, I would have done it like this:
for ($x=1; $x<=5; $x++){
if($x == 3) continue;
//some code here
}
You can use continue key word inside if statement like this; (according to PHP documentation)
<?php
for ($i = 0; $i < 5; ++$i) {
if ($i == 2)
continue
print "$i\n";
}
?>
I'am working in CodeIgniter, and want to create a dynamic breadcrumbs by using $this->uri->segment($i) function.
How should I write correctly for() statement if I want to test the 2nd expression that is not equal to FALSE ? It gives me an infinite loop and I don't know why.
here is my code:
for($i = 1; $i !== FALSE; $i++){
var_dump($this->uri->segment($i));
}
For exemple, first 3 reccursion should output a different strings, starting from 4th reccursion, it gives me false but it's not working here, know someone why ?
Your $i variable is an integer, and will never be equal to FALSE.
Maybe you are looking for comparing $this->uri->segment($i)?
for($i = 1; $this->uri->segment($i) !== FALSE; $i++){
var_dump($this->uri->segment($i));
}
can I do something like
if($x != (y&&z&&r&&w))
Or do I have to write it like this
if($x!=y && $x!=z && $x!=r && x!=w)
Just wondering because I have lots of variables to compare and just wanted a more elegant solution.
You might have a more elegant solution anyway. Here's what I'm trying to do.
foreach($_POST as $key => $value){
if($key != 'category_id'){
$cp[$key] = $value;
}
}
And I have about 6 more variables to compare in my $_POST statement and I would like to make the code pretty. It's basically a huge form that needs to format into a specific array ($cp[]) with specific keys to use my MySQL insert statement.
Any fancy ideas?
Your first portion of code :
if($x != (y&&z&&r&&w))
will evaluate the constants y, z, r and w (strings 'y', 'z', 'r' and 'w', if those constants don't exist) ; doing a AND between each one of those.
And, then, the result of this AND will be compared to $x -- which will be considered as a boolean.
So, no, it's not quite doing what you hoped for ; you must use your second portion of code :
if($x!=y && $x!=z && $x!=r && x!=w)
Note that here, too, it'll search for constants called y, z, r and w (or strings, if those constants still don't exist) -- you should probably put some $ in front of those, if you expect them to be treated as variables.
If you want to test if a variable has one of several values, a possible solution is to put those values into an array, and, then, use the in_array() function :
if (in_array($x, array(10, 20, 30) )) {
// $x is one of those values : 10, 20, 30
}
Some think it's easier to understand this way than writing several comparisons -- I sometimes use this myself, and kind of like it.
You'll have to write the long form or use in_array and an array containing your values.
You you can not do it like this:
if($x != (y&&z&&r&&w))
They have to be separated out in to 4 comparisons.
Alternatively, what you can do is stick the values in an array and have only 1 comparison:
$skip_keys = array('a', 'b', 'c', 'd');
foreach ($_POST AS $key => $value) {
if ( ! in_array($key, $skip_keys)) {
// Continue
}
}
You can't say
if ($x != (1&&2&&3))
like that
I also was wondering in my early years whether we can do
if (1 < $x < 5)
and the answer is no too. But you can use in_array() to test if something in an array for you to check several values at once:
http://php.net/manual/en/function.in-array.php
My recommendation, if you're doing this comparions multiple times, is to write a function that validates your requirements for it. So you'll pass in your '$x' and can compare that to everything you need, and will get a boolean result. The function can be structured nicely with ifs and elseifs and you'll keep your code cleaner.
So, example...
<?php
// random, bad logic, but you get the idea
function validateThisThing($x) {
$toReturn = false;
if ($x == 'this') {
$toReturn = true;
} elseif ($x == 'that') {
$toReturn = true;
}
return $toReturn;
}
Then you can just use that function as needed and keep your checks cleaner and more structured as your function name will bring context into what's being checked.