Pass variable value through nested if() statements - PHP - php

I want to be able to do the below but unable to since the values are not passed to the next if statement.
if(something){
$x=SomeValue;
if(something){
$y=SomeValue;
if($x==$y){
echo"x & y matches";
}
}
}
I also tried $GLOBALS in the respective if statements but still doesn't work.
How do I pass the values of $x & $y to the third if() statement
Actual code
if($i%2) {
$dx1 = $row['sec1'];
echo $dx1;
if($i%2==0){
$dx2 = $row['sec2'];
echo $dx2;
if($dx1==$dx2){echo $dx1." do not match ".$dx2;}
}
}
}

In PHP, any value which is not "empty" is considered "truthy"; in the case of an integer, that means 0 is false, and everything else is true. So if($i%2) means the same as if( $i % 2 != 0 ).
Later, you nest inside that if a similar-looking condition, if($i%2==0), which is actually the exact opposite. To reach the inner if, you have to first have gone into the outer if, so both conditions need to be true to reach the innermost code.
As you say, the conditions are equivalent to "$i is odd" and "$i is even". To get into the first if statement, $i must be odd; but to get into the second, it must also be even. No value of $i will ever meet both conditions, so the innermost code will never be reached.

Related

Assign variable value in php

i'm just confused about assigning variable values on php to another one , how does it work?!
for Example:
<?PHP
$var1=mysqli_fetch_array($query);
while($var2=$var1)
{
echo $var2[$key]; /** this wont't work Correctly however $var1 it's
value = to mysqli_fetch_array**/
}
while($var1=mysqli_fetch_array($query))
{
echo $var1[$key]; /** this will work , why ! **/
}
?>
A peculiarity in PHP's assignment behaviour, is that it also returns the result of the assigned value. This allows for statements such as:
$a = $b = $c = 3; // All of a, b and c will equal 3
And:
while ($variable = call_a_function()) {
do_something_with($variable);
}
In the latter example, variable gets assigned to the output of call_a_function() at the beginning of the loop iteration; as soon as call_a_function() returns a value that evaluates to false, the loop ends. If the returned value does not evaluate to false, variable will contain whatever value was returned, until it gets overwritten again.
Your examples use a similar behaviour. The crucial difference between
$var1=mysqli_fetch_array($query);
while($var2=$var1)
{
echo $var2[$key];
}
And:
while($var1=mysqli_fetch_array($query))
{
echo $var1[$key];
}
...is that in the first example, $var1 is only assigned to the return value of mysqli_fetch_array($query) before the loop starts, while in the second example, $var1 is assigned to the return value of mysqli_fetch_array($query) in every iteration of the loop.
What makes the two pieces of code crucially different, in the end, is the fact that mysqli_fetch_array($query) returns different results, depending on circumstances.
Combining the code snippets into an example that works as intended, yet uses $var2, yields:
while($var2=$var1=mysqli_fetch_array($query))
{
echo $var2[$key];
}
or
$var1=mysqli_fetch_array($query); // ask first time
while($var2=$var1)
{
echo $var2[$key];
$var1=mysqli_fetch_array($query); // ask again, because the answer changed
}
TL;DR: The first example asks a question once, the second asks a question many times. In this case, the intended behaviour of your code requires the question to be asked multiple times, because the answer changes over time.

Continue to the next loop in a foreachloop with another nested foreachloop

I have 2 Foreach-Loops. One of them is nested inside the other, e.g.:
foreach(...){
foreach(...){
//if statement
}
}
Within the inner loop I got an if statement and if this statement returns true I want to break the inner loop and continue with the next outter loop. Is there any way to realize this? "break 2; " won't work as I need to continue with the outter loop.
Like with break, you can add a number to continue as well:
foreach(...) {
foreach(...) {
if (...)
continue 2;
}
// this will be skipped
}
From the docs:
continue accepts an optional numeric argument which tells it how many
levels of enclosing loops it should skip to the end of. The default
value is 1, thus skipping to the end of the current loop.
Per PHP documentation, the default is 1, which only breaks out of the immediately encapsulating control struct
break ends execution of the current for, foreach, while, do-while or
switch structure.
break accepts an optional numeric argument which tells it how many
nested enclosing structures are to be broken out of. The default value
is 1, only the immediate enclosing structure is broken out of.
For example, the below code:
<?php
foreach(array(1,2,3,4,5) as $num){
foreach(array('a', 'b') as $char){
if($char === 'b') {
break;
}
echo $char;
}
echo $num;
}
// Result: a1a2a3a4a5
It breaks before it prints 'b', but continues with the loop to 5.

Local/Global vars in PHP

I'm a newb. I have several tables to store forms and I want the next user's input to be stored the table with the least responses (each form is different).
I've taken the rowcounts from the sql db and they are working. I use the code below detect how many responses there are and hence set $testnumber accordingly.
The code fails. Essentially, when I echo $testnumber, it doesn't matter what values the row counts are, it just randomises according to the first if statement.
When I delete the first if statement, I get an error saying that $testnumber is undefined regardless of the values of rowcounts.
I am absolutely confused the hell out. In my head the var $testnumber is local in all of the statements (they are not defined elsewhere) so they should all either work or not work.
I would appreciate some help. I know my if statements are crap and doesn't cover all cases so any help here would be useful but most IMPORTANTLY can you explain why my other statements are being ignored and why the first one isnt?
Thank you
if ($rowcount1 = $rowcount2 = $rowcount3 = $rowcount4){ // if all rowcounts are equal
$testnumber = mt_rand(1,4);
}
if ($rowcount1 < $rowcount2){ //rowcount for 1 is lowest
if($rowcount1 < $rowcount3){
if($rowcount1 < $rowcount4){
$testnumber = 1;
}
}
};
if ($rowcount2 < $rowcount1){ // rowcount for 2 is lowest
if($rowcount2 < $rowcount3){
if($rowcount2 < $rowcount4){
$testnumber = 2;
}
}
};
if ($rowcount3 < $rowcount1){ // rowcount for 3 is lowest
if($rowcount3 < $rowcount2){
if($rowcount3 < $rowcount4){
$testnumber = 3;
}
}
};
if ($rowcount4 < $rowcount1){ //rowcount for exp2 is lowest
if ($rowcount4 < $rowcount2){
if ($rowcount4 < $rowcount3){
$testnumber = 4;
}
}
};
echo "Final Testnumber: " . $testnumber;
Your first comparison statement isn't a comparison at all: single = sets a variable, double == tests for equality. Thus, your conditional will always evaluate to TRUE, because it's setting your variables correctly.
On top of that, you need to expand out your statements, as equality comparisons don't work this way in PHP.
if (($rowcount1 == $rowcount2) && ($rowcount2 == $rowcount3) && ($rowcount3 == $rowcount4)){ // if all rowcounts are actaully equal
Check out the relevant PHP docs: Assignment Operators, Comparison Operators
Edit: Your next conditional statements are hampered by the fact that it appears you're running into issues with Variable Scope. Basically, in order to access the $testnumber variable, you'll need to define it outside the "scope" of a conditional block.
$testnumber = 0;
if (($rowcount1 == ...
While outside the scope of the question: based on what you've provided here, it may be worthwhile to check out the PHP documentation on arrays, it will help you immensely as you start to scale your code up.

PHP - Exit For Loop After Wrong Answer

I'm trying to teach myself PHP. My current exercise combines a form (not included in the code, but it works) that requires the user to enter the name of a city. The loop and the if statement compare the entry with an array of state capitals to return an answer that states whether that city is a state capital or not.
If I leave out the elseif part, the code runs ok, but I have no alternative when the user has entered a city that is not in the array. But with the elseif, the first part of the loop doesn't execute. For example, if I enter "Albany" without the elseif, I get "Albany is the capital of New York." But if I enter it with the elseif statement, it runs the loop until it finds "New York" and it prints "Albany is the capital of New York."
I've googled this, and I've read the books on PHP that I have. And I also know that I'm making a very basic mistake. Any guidance would be greatly appreciated.
for ($i = 0 ; $i < count($stateCapitalNames); $i++)
if ($enteredCity == $stateCapitalNames[$i]) {
print "<p>$enteredCity is the capital of <b>$stateNames[$i]</b>. </p>";
} elseif ($enteredCity != $stateCapitalNames[$i]){
print "<p>$enteredCity is not the capital of a state.</p>";
}
?>
You can use break to leave the for loop.
You should look at array_search to find the index you are looking for. array_search returns false if the capital does not exist.
For instance
$i = array_search($enteredCity, $stateCapitalNames);
if($i !== false)
{
echo "<p>$enteredCity is the capital of <b>",$stateNames[$i],"</b>. </p>";
}
You are missing your brackets in your for loop. I'm surprised the elseif is the culprit and that the code doesn't fail anyways. But here is what I would do, errors aside:
$correct = false;
for ($i = 0 ; $i < count($stateCapitalNames); $i++){
if ($enteredCity == $stateCapitalNames[$i]) {
$correct = true;
$stateNames = $stateNames[$i]; // Updated $stateNames variable
break;
}
}
//You can check $correct here...
if($correct){
print "<p>$enteredCity is the capital of <b>$stateNames[$i]</b>. </p>"; /*Removed [$i] from $stateNames. For some reason, $stateNames[$i] wasn't updating outside the loop, but now it is.
}
This way, no matter what, until the code finds a correct answer, the user is wronge. Once it finds the right answer, it sets it as correct and exits the loop by setting $i to the length of the array.

Strange Boolean Reaction

$alerter2="false";
for ( $counter = 0; $counter <= count($filter); $counter++) {
$questionsubmitted=strtolower($_POST[question]);
$currentcheck =$filter[$counter];
$foundvalue=stripos((string)$questionsubmitted,(string)$currentcheck);
echo $foundvalue;
if ($foundvalue==0) {
$alerter2="true";
} else { }
}
if (!($alerter2=="true")) {
$sql="INSERT INTO Persons (Name, Email, Question)
VALUES
('$_POST[name]','$_POST[email]','$_POST[question]')";
} else {
echo "Please only post appropriate questions";
}
For some reason, whenever I run this, stripos returns 0 every time for every iteration. It's supposed to be a filter, and using echo I found that stripos is 0 every time that it appears. However, when I use 0 in the if, it returns true for even those that don't have the word in them.
Where should I use mysql_real_escape_string? After the query? Note, I am making this a piece of code where I want user input to be saved to a database.
stripos return false if the value is not found, or 0 if it is the first character. Problem is, php automatically cast boolean to the 0 integer or the 0 integer to false. So I think a cast is happening here and thus the condition don't do what you want.
You can use === to also check the type of the variable :
if ($foundvalue === 0) {
$alerter2="true";
}
There's more details about this problem in the linked documentation for stripos.
You should also remove the empty else clause for a cleaner code and use mysql_real_escape_string to sanitize the values before putting them in your database.
You need to change
if ($foundvalue==0)
to
if ($foundvalue===0) // three equals signs
or something equivalent, depending on your logic (I didn't quite understand what's going on).
But as everyone says, THIS CODE IS OPEN TO SQL INJECTION ATTACKS (among other problems).
Also,
$questionsubmitted=strtolower($_POST[question]);
should probably be:
$questionsubmitted=strtolower($_POST['question']);

Categories