简体   繁体   中英

PHP - Change a variable's value for a later If statement within another variable

I am trying to create a $clause variable that contains the variable $team1 and can change the value of the variable $team1 for a later If statement.

Below is a simplified version of my code:

$team1 = "";

$clause = "$team1 == 'Wildcats' OR $team1 == 'Bulldogs";

$team1 = 'Bears';

if ($clause) { echo "Yes"; }
else {echo "No";}

I would like $clause in the If statement to have the value (in this example):

'Bears' == 'Wildcats' OR 'Bears' == 'Bulldogs";

No matter what I make the value of $team1, the output is "Yes". How can I get the If statement to correctly determine if value of $team1 is (or isn't) meeting the condition in $clause?

Your if statement checks whether or not the variable is declared or not. So it will always print "Yes".

The type you want can be acheived by using eval which translates text into PHP-Code.

See http://php.net/manual/de/function.eval.php for further instructions.

use with some return function .Because variable already printed the value in first definition .so call function after if condition satisfied .Then new variable value was updated

    function varReset($team1){
    return "$team1 == 'Wildcats' OR $team1 == 'Bulldogs";
}
$team1 = "";
$clause = varReset($team1);
$team1 = 'Bears';
if ($clause) {
    $clause = varReset($team1);
    echo $clause;
    echo "Yes";
}
else {echo "No";}

I think your question is illogical because Php will execute statement line by line, so $cause value will be (== 'Wildcats' OR == 'Bulldogs') and then if($cause) -- will return TRUE because if will check the variable is 'isset' and 'not empty', It won't take as you expected condition I recommend you to use function

function checkVal($param) {
    return ($param == 'Wildcats' || $param == 'Bulldogs') ?  "Yes" : "No";
}

echo checkVal('Bears');

Based on the feedback, I decided that I needed different approach to solve this problem. I was able to get what I wanted by putting the teams into an array ($teams) and then looping through that array with the If statement comparing to $team1. The following code works how I want it to by changing the value of $team1.

$teams = array('Wildcats', 'Bulldogs', 'Cougars');
$team1 = 'Bears';

$count = 0;
$met = "no";

do {
    if($team1 == $teams[$count]) { $met="yes"; break;}
    $count++;
} while ($count < count($teams));


echo $met;

Thanks to everyone for the help! I've used this forum a lot to solve previous problems, but this is the first time I've actually posted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM