single = on while loop - php

i'm practicing php at nowadays. i have one question.
i see one = on some while loops. often on mysql queries. so what does it stands for?
two == means equal. but single = ? can you tell me the logic behind this?

Single = means "assignment". An assignment always assigns to a variable and returns the result. So, for example:
while($row = mysql_fetch_array($results)) {
// ...
}
While mysql_fetch_array($results) returns a valid array, it loops. When it returns null (meaning that's the end of the results) the loop exits.

while ($row = mysql_fetch_row($query))
{
//do stuff
}
This keeps querying the result handle until a NULL value (end of result) is found. $row then contains the row fetched from the call so it can be used for processing.
It is also "shorthand" for checking for a NULL result:
while (($row = mysql_fetch_row($query)) != null)
{
//do stuff
}
It can also replace a for loop:
for ($i = 0; $i < mysql_num_rows($query); $i++)
{
//do stuff
}
All are equivalent.

single = is for assignment
$a = 9;
== is for comparison
if($a == 9) echo 'hello';
http://www.w3schools.com/PHP/php_operators.asp

That's the assignment operator.

While the current value of 'x' can be successfully assigned to variable 'y', continue on.

Here is an alternative:
$row = mysql_fetch_assoc($thing);
while (isset($row)) {
// do stuff
$row = mysql_fetch_assoc($thing);
}
You can see that it's a bit less typing (and the code is probably more efficient) here:
while (($row = mysql_fetch_assoc($thing)) != null) {
// do stuff
}

Related

Why does this PHP assignment in a loop always print the first value?

I'm very confused as to the output of this small piece of test code:
<?php
$count = 0;
while ($fn_retval = do_the_thing($count) !== false) {
print $fn_retval."\n";
$count++;
}
function do_the_thing($count) {
if ($count > 3) {
return false;
} else {
return $count;
}
}
?>
The output is:
$ php ./test.php
1
1
1
1
So it is correctly performing 4 iterations but always printing the return value of the first iteration. I feel like I must have missed something really obvious because this makes no sense.
Can somebody explain what's going on here because it seems like I can't use that assign-and-check construct in the way I thought I could.
The problem is that the order in which
$fn_retval = do_the_thing($count) !== false
is evaluated. If you check the Operator Precedence, you will see that !== is a higher precedence than =, so it's evaluated as
do_the_thing($count) !== false
and the result is then assigned to $fn_retval.
To force the order you are after, use brackets to explicitly do the assignment first...
while (($fn_retval = do_the_thing($count)) !== false) {

I can't put a value in the array?

I made an iterative loop and created two matrices and I want when I find a specific name I put the corresponding value from the other row in the J variable but I gave me the wrong result which is the number 8 where the number was supposed to appear 7
// my code:
<?php
include 'DB.php';
$db=DB::getInstance();
//$posts = $db->table('posts')->get();
//echo json_encode($posts);
//$users = $db->table("posts")->Qget();
$rows = $db->table('posts')->get();
$filter_value1 = [];
$filter_value2 = [];
$i=0;
$j=0;
foreach($rows as $row){
$filter_value1[]=$row->name;
$filter_value2[]=$row->user_id;
if($filter_value1[$i]="gmal"){
$j= $filter_value2[$i];
}
// echo "$row->name <br>";
$i++;
}
echo($j);
= : This is an assignment operator in any Language suppose we want to assign some value to a variable we will use (equal to) = sign. It does not return anything. e.g.
$name= "gmal";
== : This is a comparison operator. If we want to compare two values or values hold by variables we should use ==. This operator returns True /False bases on comparison e.g.
if("22" == 22) it will return true
=== : Checks the values as well as the type of operands.
if("22" === 22) it will return false
if($name == "gmal"){
echo "Name is : {$name}";
}
so in your code change the following line
if($filter_value1[$i]="gmal")
to
if($filter_value1[$i] == "gmal")

Why is only of my two variable increment statements working?

This is driving me nuts. I've spent a couple hours trying to debug this but I'm getting nowhere. $total should increment by 1 everytime $result != 'REMAKE' but it's only incrementing whenever $result == 1 (and not when $result == 0). I cannot figure out why. I've tried $total += 1 but it makes no difference.
didAccountWinMatch() will return either 0, 1, or 'REMAKE'.
$total = 0;
$wins = 0;
if (isset($match)) {
foreach ($match as $key => $value) {
$result = didAccountWinMatch($accountId, $match[$key]);
if ($result != "REMAKE") {
$total ++;
$wins += $result;
}
}
} else {
$total = 0;
$wins = 0;
}
Use !== instead of !=. If you use the loose comparison operator between an integer and a string, the string is converted to an integer first. Converting the string REMAKE to an integer results in 0, so the code is equivalent to
if ($result != 0)
when $result is an integer.
The strict comparison operator !== doesn't perform type conversion; if the operands are different types it returns false.

This PHP if loop should be the most, strangest question here, but I do want to know

This first loop executes when $cnt=3 and the other other than $cnt=3. Whatever the value of $cnt only the first loop executes whether $cnt=3 or $cnt==3.
$ary = explode(".", $string);
$cnt = count($ary);
if ($cnt="3") {
//executes when cnt=3
$fnm = $d[0];
$fnxt = $d[1].".".$d[2];
} else {
//executes when anything other than when cnt=3
$fnm = $d[0];
$fnxt = $d[1];
}
I might be missing something here, what exactly wrong here?
Thanks
Jean
You're missing an = sign on the comparison. It should be:
if ($cnt == 3)
As it is, you're assigning 3 to $cnt, and since the assignment operator returns its value, the test becomes if (3), which of course always succeeds.
NB: count() returns an integer, which is why my version above compares against 3 rather than "3"
You are missing an "="
if ($cnt="3") { // This is an assignment, which returns true.
This should be:
if ($cnt == "3") { // This is a comparison.
$cnt="3" assigns the value "3" to $cnt, and the expression as a whole evaluates to "3", which is true, which causes the if block to always be executed. In order to test whether $cnt is equal to "3", use the == operator: $cnt == "3".

Strange IF Statement behaviour

I have an IF statement that consists of two separate function calls
passing values to two variables. Obviously if neither value is 'FALSE'
then the code block is executed:
<?php
class MyValidater {
static function validateString($string) {
if (preg_match("/[A-Za-z]+/", $string)) {
return $string;
} else {
return false;
}
}
}
$firstName = "Daniel";
$surname = "Simmons";
// Dodgy IF statement
if ($first = MyValidater::validateString($firstName) && $second = MyValidater::validateString($surname)) {
print("Success: $first $second");
} else {
print("Fail: $first $second");
}
?>
As you can see both the $first and $second variables should contain
the values held in $firstName and $surname after successfully being
validated by the Static method validateString.
However, the values of the two variables end up: $first = '1' and
$second = "Simmons".
The '1' should be "Daniel" but for some reason $first is being passed
the value '1' or TRUE. If you swap the two assignment statements over
so that $second is evaluated first, you end up with the opposite
outcome as before. $second = '1' and $first = "Daniel"
Can anyone explain why the String value "Daniel" being returned from
the class method is being changed into the int '1' for the first part
of the conditional statement only? I have had a quick look though the
PHP documentation but cannot find an explanation.
For the moment the workaround is to change the return value from the
static method to be true/false and then make $first = $firstName,
etc... upon success. But this involves more code and I would rather
find out why this way does not work.
You need to bracket your expressions:
if (($first = MyValidater::validateString($firstName)) && ($second = MyValidater::validateString($surname)))
What's actually happening is this:
if ($first = (MyValidater::validateString($firstName) && $second = MyValidater::validateString($surname)))
It would be much clearer to just do this (note this code isn't identical to what you have):
$first = MyValidater::validateString($firstName);
$second = MyValidater::validateString($surname);
if ($first && $second)
&& is higher then = in the operator precedence. add brackets and it will work.
http://www.php.net/manual/en/language.operators.precedence.php
you can read about operator precedence here.
Also, setting values inside of an if condition is usually bad practice. If you add the brackets, you will most probably see why (let $first set to false and $second set to a string) => the first will be evaluated, but since it is false then, it won't process further since it will go to the else anyways. => second will not be set correct if first = false.
Try using parenthesis
($first = MyValidater::validateString($firstName)) && ($second = MyValidater::validateString($surname)))
First is getting the result of the first function call AND the second function having a value.
= is for attributions
== is for comparisons, the data type doesn't matter
=== is for comparisons, the data type matters
What is happening is that PHP is assigning $first with “MyValidater::validateString($firstName)) && $second = MyValidater::validateString($surname)”
You need brackets around first compare and second, like this.
if ( ($first = MyValidater::validateString($firstName)) && ($second = MyValidater::validateString($surname))) {

Categories