PHP: Assign multiple variables in if statement - php

I don't seem to be able to assign multiple variables in an "if" statement. The following code:
<?php
function a ($var)
{
if ($var == 1)
{
return 'foo';
}
return false;
}
function b ($var)
{
if ($var == 1)
{
return 'bar';
}
return false;
}
if ($result1 = a(1) && $result2 = b(1))
{
echo $result1 . ' ' . $result2;
}
?>
Returns "1 bar" rather than "foo bar". If I remove the second condition/assignment it returns "foo".
Is there a way to assign multiple variables in an "if" statement or are we limited to just one?

This is all about operator precedence
<?php
function a ($var)
{
if ($var == 1)
{
return 'foo';
}
return false;
}
function b ($var)
{
if ($var == 1)
{
return 'bar';
}
return false;
}
if (($result1 = a(1)) && ($result2 = b(1)))
{
echo $result1 . ' ' . $result2;
}
?>
https://repl.it/IQcU
UPDATE
assignment operator = is right-asscoiative, that means, evaluation of operand on rhs has precedence over the lhs operand.
thus,
$result1 = a(1) && $result2 = b(1)
is equivalent of,
$result1 = (a(1) && $result2 = b(1))
which evaluates
$result1 = ("foo" && [other valild assignment] )
which will result that,
$result1 becomes true
and echo true/string value of boolean true (strval(true)) outputs/is 1
you can also check that revision, https://repl.it/IQcU/1
to see that below statement
$result1 = a(1) && $result2 = b(1)
is equivalent of this one.
$result1 = (a(1) && $result2 = b(1))

Need to add parentheses() in each assignment like below:-
if (($result1 = a(1)) && ($result2 = b(1)))
{
echo $result1 . ' ' . $result2;
}
Output:- https://eval.in/804770
Correct explanation is given by #marmeladze here:-
Why 1 bar is coming through OP's code

The last if statements need some brackets, it should have been:
if (($result1 = a(1)) && ($result2 = b(1)))
{
echo $result1 . ' ' . $result2;
}
This ensures that things in the bracket are executed first and it will help.

You have to add == to check a condition.
Try this,
if ($result1 == a(1) && $result2 == b(1))
{
echo $result1 . ' ' . $result2;
}
Checked with belo example
<?php
function a ($var)
{
if ($var == 1)
{
return 1;
}
return false;
}
function b ($var)
{
if ($var == 1)
{
return 2;
}
return false;
}
if (1 == a(1) && 2 == b(1))
{
echo 'success';
}
?>

Related

If logic (predicate expression) in a variable

I'm passing the comparison operator as a variable to the PHP Cli:
./test.php -k "command" -c ">0"
The command in -k products a result and I've stored it in $result
The problem I'm getting is I want to pass the logic and comparison operator as variables, is this possible?
$result = 2;
$logic = ' >0';
if ( $result $logic ) echo "true";
But I get:
PHP Parse error: syntax error, unexpected '$logic' (T_VARIABLE)
Any ideas?
It's not possible to do it that way, but you can do it using the eval method, like this:
$result = 2;
$logic = ' >0';
eval('$logicResult = ' . $result . $logic .';');
if ( $logicResult ) echo "true";
The eval method is not recommended, as it might introduce security flaws in your app.
While eval does the trick, it is generally considered harmful.
If the universe of possible operator instances in $logic is limited, better work with a switch statement or a cascaded if:
$result = 2;
$logic = trim(' <0');
$op2 = substr($logic, 0, 2);
$op1 = substr($logic, 0, 1);
if ( $op2 == '>=') {
$operand = substr($logic, 2);
if ($result >= (int)$operand) { echo "true"; }
} elseif ( $op1 == '>' ) {
$operand = substr($logic, 1);
if ($result > (int)$operand) { echo "true"; }
} elseif ( $op1 == '=' ) {
$operand = substr($logic, 1);
if ($result == (int)$operand) { echo "true"; }
} elseif ( $op2 == '<=') {
$operand = substr($logic, 2);
if ($result <= (int)$operand) { echo "true"; }
} elseif ( $op1 == '<' ) {
$operand = substr($logic, 1);
if ($result < (int)$operand) { echo "true"; }
} else {
echo "operator unknown: '$logic'";
}
As #treyBake notice, you can use eval() - Evaluate a string as PHP code:
<?php
$result = 2;
$logic = 'if(' . $result . '>0){echo "true";};';
eval($logic);

Is it possible to do a statement within a statement?

So I'm trying to do something like this
if($id == 1 || $id == 2 || $id == 5 || $id == 8) {
echo 'test';
} elseif($id == 6) {
echo 'test2';
} else {
echo 'error';
}
It's so I can show a specific message (with html etc in the finished version) when the id obtained via post method is different.
EDIT: The issue is the code repeats itself twice.
How could I go about resolving this?
Thanks to anyone who contributes into helping me with this!
Use in_array().
$arr = [1,2,5,8];
$id = 1;
if(in_array($id, $arr)) {
echo 'test';
} elseif($id == 6) {
echo 'test2';
} else {
echo 'error';
}
https://3v4l.org/T5giX
As i see you have more than 3 id to compare so easy Solution is take all id as an array
And use in_array.
<?php
$id = 3;
$myid = array(1,2,5,8);
if(in_array($id,$myid)) {
echo 'test';
} elseif($id == 6) {
echo 'test2';
} else {
echo 'error';
}
Also You Can Use PHP Switch Statement
<?php
$id = 6;
switch ($id) {
case 1:
case 2:
case 5:
case 8:
echo "Passed .!";
break;
case 6:
echo "Passwd 2!";
break;
default:
echo "Failed .!";
}
to make this statement in one line use ternary operator. hope it satisfy you.
echo ( ($id == 1 || $id == 2 || $id == 5 || $id == 8) ? "test" : (($id == 6) ? "test2" : "error"));

PHP empty variable inside condition

I have a condition in which it is using a variable to pull either a number through 0-17, the string "MAKEUP", or the variable will be empty. I would like it to output the text "WIN" if the variable is greater than the number 8 and "LOSS" if the variable is less than the number 9. I would also like it to out "MAKEUP" if the variable consist of the string MAKEUP, and to display nothing if the variable is empty. Seems pretty simple to me, but I'm having issues particularly with the empty part. Can anyone let me know what I am doing wrong here? Code below
<?php
$t1w8 = '';
$result = $t1w8;
if ($result > 8 && !empty($result)) {
echo 'WON';
} elseif ($result < 9 && !empty($result)) {
echo 'LOSS';
} elseif ($result == 'MAKEUP') {
echo '-';
} else {
echo 'yooo';
}
?>
Make some changes in your conditions like this
<?php
//$result = "MAKEUP";
$result = 0;
if ($result === 'MAKEUP') {
echo '-';
}else if (is_numeric($result) && $result < 9 ) {
echo 'LOSS';
}else if (is_numeric($result) && $result >= 9 ) {
echo 'WON';
} else{
echo 'yooo';
}
?>
Live demo : https://eval.in/897120
try with this code
<?php
//$result = "MAKEUP";
$result = "";
//$result = "9";
//$result = "-";
if ($result == 'MAKEUP' && !empty($result) ) {
echo '-';
} elseif ($result > 8 && !empty($result)) {
echo 'WON';
} elseif ($result <= 8 && !empty($result)) {
echo 'LOSS';
} else {
echo 'yooo';
}
?>
for demo :demo code here
You have explained that your number range is from 0-17.
You have also explained that you could get the word MAKEUP.
Based upon those constraints we could use something like this
$output = "";
// Do we have something?
if(strlen($result) > 0) {
if (strtolower($result) == "makeup") {
$output = "MAKEUP";
}
// assumes a single digit string
else if ($result < 9) {
$output = "LOSS";
} else if ($result <= 17) {
$output = "WIN";
}
}
echo $output;

Put IF condition inside a variable

Is there any way to put conditions within a variable and then use that variable in an if statement? See the example below:
$value1 = 10;
$value2 = 10;
$value_condition = '($value1 == $value2)';
if ($value_condition) {
echo 'It works!';
} else {
echo 'It doesnt work.';
}
I understand this may be a bizarre question. I am learning the basics of PHP.
No need to use strings. Use it directly this way:
$value1 = 10;
$value2 = 10;
$value_condition = ($value1 == $value2);
if ($value_condition) {
echo 'It works!';
} else {
echo 'It doesnt work.';
}
Or to evaluate, you can use this way using ", as it expands and evaluates variables inside { ... }.
I reckon it might work! Also, using eval() is evil! So make sure you use it in right place, where you are sure that there cannot be any other input to the eval() function!
Depending on what you are trying to do, an anonymous function could help here.
$value1 = 10;
$value2 = 10;
$equals = function($a, $b) {
return $a == $b;
};
if ($equals($value1, $value2)) {
echo 'It works!';
} else {
echo 'It doesnt work.';
}
However, I would only do it like this (and not with a regular function), when you make use of use ().
== operator evaluates as a boolean so you can do
$value1 = 10;
$value2 = 10;
$value_condition = ($value1 == $value2);
if ($value_condition) {
echo 'It works!';
} else {
echo 'It doesnt work.';
}
Just assign result of comparision to variable.
$value1 = 10;
$value2 = 10;
$value_condition = ($value1 == $value2);
if ($value_condition) {
echo 'It works!';
} else {
echo 'It doesnt work.';
}
An if statement tests a boolean value. You could have something like this:
if (true) {
You can assign boolean values to a variable:
$boolValue = true;
You can use variables in your if statement:
if ($boolValue) {
// true
In your example:
$value_condition = $value1 == $value2; // $value_condition is now true or false
if ($value_condition) {

Confusion with `if` `else` and `while`

I have a code where it should check if the result equals to 8 it need to show something and if not it need to show something else and all of that happens inside of a while loop.
while ($row_fpages2 = mysql_fetch_array($result_fanpage2))
{
if ( $row_fpages2['client'] != NULL ) {
//GRAPHS
$sql = "SELECT likes, date FROM statistics_pages WHERE idnum = '".$idnum."' AND page_name = '".$row_fpages2['page_name']."' ORDER BY `statistics_pages`.`date` DESC LIMIT 8";
$result2 = mysql_query($sql) or die(mysql_error());
if ($result2) {
$data = array();
while ($row = mysql_fetch_assoc($result2)) {
$data[] = $row["likes"];
}
if ($result2 == 8) {
$c_data = count($data)-1;
$final = array();
for ($i = 0; $i < $c_data; $i++) {
$final[] = getZeroResult($data[$i], $data[$i+1]);
}
$data_string = join(",", $final);
$stats = '<img src="http://chart.apis.google.com/chart?chs=240x140&cht=ls&chd=t:0,0|'.$data_string.'&chg=20,20&chls=0.75,-1,-1|6,4,1&chm=o,FF9900,1,-1,7,-1|b,3399CC44,0,1,0"></img>';
} else {
$stats = '<img src="images/stats_un.jpg"></img>';
};
} else {
print('MySQL query failed with error: ' . mysql_error());
}
echo '...';
The problem is that the first output always showing the ( == 8) (even if it is not equals to 8) instead of the else output.
Then if i have 2 or more everything comes above the first one is correct but the first one is still showing the ( == 8).
Any help?
You do the following which is incorrect:
$result2 = mysql_query($sql) or die(mysql_error());
...
if ($result2 == 8) {
The return value of mysql_query is a resource not an int. What is that you are trying to do there ?
May be you would like to use
if(strlen($result2) == 8){
...
}
instead of
if($result2 == 8){
...
}
Hope that solves your problem.

Categories