for() statement in PHP if not equal to FALSE - php

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));
}

Related

What kind of conditions can I use in a for loop using PHP?

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! :)

What is the reason of returning -1 instead of lets say 0 at the end of this function's code?

I am talking about the second "return -1;" on the 12th line of the code. This gets reached only if two sets of numbers are exactly the same, like when comparing '192.167.11' to '192.167.11'. I will also add that using range(0,2) would be a better option for this piece of code (range(0,3) produces errors if two elements happen to be the same; I did not change that as this is the original code example from PHP Array Exercise #21 from w3resource.com).
<?php
function sort_subnets($x, $y){
$x_arr = explode('.', $x);
$y_arr = explode('.', $y);
foreach (range(0, 3) as $i) {
if ($x_arr[$i] < $y_arr[$i]) {
return -1;
} elseif ($x_arr[$i] > $y_arr[$i]) {
return 1;
}
}
return -1;
}
$subnet_list =
array('192.169.12',
'192.167.11',
'192.169.14',
'192.168.13',
'192.167.12',
'122.169.15',
'192.167.16'
);
usort($subnet_list, 'sort_subnets');
print_r($subnet_list);
?>
Returning "-1" would move the second element (the same as the first in the current $x and $y pair) towards the higher index of the array (down the array). Why not return "0" and keep everything as is if the two elements are exactly the same? Is there any reason for returning the "-1" maybe based on how the usort() works (or any other factor of this)?
Thanks.
EDIT:
I think that this is Insertion Sort (array size 6-15 elements; normally it would be Quicksort).
If the two elements are the same, there's no difference between swapping the order and keeping the order the same. So it doesn't make a difference what it returns in that case.
You're right that 0 is more appropriate. This would be more important if usort were "stable". But the documentation says
Note:
If two members compare as equal, their relative order in the sorted array is undefined.
To illustrate the excellent point of #Don'tPanic:
<?php
function sort_subnets($x, $y){
$x_arr = explode('.', $x);
$y_arr = explode('.', $y);
return $x_arr <=> $y_arr;
}
$subnet_list =
array('192.169.12',
'192.167.11',
'192.169.14',
'192.168.13',
'192.167.12',
'122.169.15',
'192.167.16'
);
usort($subnet_list, 'sort_subnets');
print_r($subnet_list);
See live code
Note the use of the "spaceship" operator, namely <=> which offers a conciseness that spares one from having to write code like the following in a function:
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
Lastly, note that the user-defined callback for usort() makes use of ternary logic because sometimes as in the case of sorting bivalent logic is insufficient. Yet, usort() itself utilizes two-part logic, returning TRUE on success and FALSE on failure.

Is there something wrong with my for loop/if statement?

I have a for loop within a for loop and right before I enter an if statement, two values echo out and are equal. When I evaluate (with the if statement) whether or no they are equal, the values do not evaluate to even. Could there be something that I am not seeing that is wrong with this statement?
for($x = 0; $x < count($movies_total);$x++){
for($j = 0; $j < count($ask_array);$j++){
echo $movies_total[$x]->question_id.' '.$ask_array[$j].'<br>';
if($movies_total[$x]->question_id == $ask_array[$j]){
echo 'no';
}
}
}
You should dump both your variables ( $movies_total[$x] , $ask_array ) for us to know the problem but my guess would be you have white spaces. You can compare variables after trim:
if( trim($movies_total[$x]->question_id) == trim($ask_array[$j]) )

Difference between an If statement and While loop

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.

PHP - use variable as operator

I am trying to get this:
if($a[2] > $b[2] && $c[2] < 3) echo "bingo";
But because the condition is retrieved from database, I need to get the whole condition into a variable and then somehow find a way to change the variable back into a condition. I thought it will be something along this line:
$condition = "$a[2] > $b[2] && $c[2] < 3";
$evaledCondition = eval("$condition;");
if($evaledCondition) echo "bingo";
Apparently it didn't work. Am I missing something?
eval() returns NULL unless return is
called in the evaluated code
$evaledCondition = eval("return $condition;");

Categories