PEG-php parsing if statement - php

Good day.
Just started to use PEG.
I'm familiar with wp:peg
and some other theory, but still can't understand how it internally works.
My task is to parse expressions like
if($a=='qwerty' && $b>2 || $c<=5)
print 'something';
endif;
Body of is statement contains only print operator and nothing else, but it has complex condition.
My thinking about it:
/*!* Calculator
Int: /[0-9]+/
Var: /\$[a-z]+/
tThen: /then{1}/
tIf: /if{1}/
tElse: /else{1}/
tEndif: /endif{1}/
block: /.+/
condEq: Var '==' ( Int | Var ) *
condStatement: '(' condEq ')'
function condEq( &$result, $sub ) {
if( eval($sub['text'].';') ) {
$result['text'] = 'true';
}
else {
$result['text'] = 'false';
}
}
ifStatement: tIf condStatement
Expr: ifStatement
*/
But I believe this task has better solution:)
Can you help me with it?
Thanks.

Related

variable assign and check

Can Someone tell me what's wrong with this code
function someFunction($num=null) {
return $num;
}
if ($name = someFunction('mystr') && $name ) {
echo 'hello ';
}else {
echo 'hi';
}
Why it is going in else condition and giving me notice of undefined variable $name
Edited: - if i do like this
if($name = someFunction() && $name ){
echo 'hello';
} else {
echo 'hi';
}
this time its also going on else condition as it should but it also not showing the error as i understand it, php just check my first condition $name = someFunction() and its fail then just else
but if i do as i do previously $name = someFunction('str') now $name is set so why notice of undefined variable
sorry for bad grammer
just want to know what is happening here.
It's because logical operators like && have higher precedence than the assignment operator =. You can read more about this here: http://php.net/manual/en/language.operators.precedence.php
The line
if ($name = someFunction('mystr') && $name ) {
is being evaluated like this:
if ($name = (someFunction('mystr') && $name) ) {
where the expression in the inner brackets is evaluated first. Because $name has not been defined before this point, a notice is raised.
I think what you're trying to do is this:
if (($name = someFunction('mystr')) && $name ) {
where you assign the value mystr to $name and then also evaluate that it's "truthy". But as pointed out in the comments, this is a bit of a strange approach. The following code would be equivalent:
$name = 'mystr';
if ($name) {
...
This feels a bit like a problem that's been cut down a bit too much in order to explain it, because it's not really clear why you're doing this.
you code output : hi becuase there is $name is in second is always null.
function someFunction($num=null) {
return $num;
}
$name = someFunction('mystr');
if ($name && $name ) {
echo 'hello ';
}else {
echo 'hi';
}
output : mystr && mystr = 1 then output is hello
You haven't assigned anything to your variable $name and since it is an AND Condition, the first gets true but the second one doesn't so assign any value to your $name and add a condition for it to work.

Checking if PHP Variables are and aren't NULL

UPDATE:
The following code
function findNowPlayingCondition () {
if (isset($nowplayingname) && isset($nowplayingartist)) {$nowplayingcond = '1'; };
if (isset($nowplayingname) && !$nowplayingartist) {$nowplayingcond = '2'; };
if (!$nowplayingname && isset($nowplayingartist)) {$nowplayingcond = '3'; };
if (!$nowplayingname && !$nowplayingartist) {$nowplayingcond = '4'; };
echo "$nowplayingcond";
}
always comes back with '4', again, I am stumped.
====================
I am trying to create a PHP if/then statement that if $nowplayingname has a valid string in it, and $nowplayingartist is not set, is '', or is NULL, it will set $nowplayingcond as '2'.
if (var_dump(isset($nowplayingname)) && !$nowplayingartist) {$nowplayingcond = '2'};
I am getting a parse error when this executes, I suspect it has something to do with var_dump(isset(, but I am not certain.
This will do.
if(!empty($nowplayingname) && !isset($nowplayingartist))
{
$nowplayingcond = 2;
}
To fix the syntax error:
if (var_dump(isset($nowplayingname)) && !$nowplayingartist) {$nowplayingcond = '2';};
// ---^
Further suggestions:
Indent your code properly and don't use one-liners that way:
if (var_dump(isset($nowplayingname)) && !$nowplayingartist) {
$nowplayingcond = '2';
}
Why do you use var_dump() in an IF statement? Apart from the fact that var_dump()'s return value will always evaluate to a falsy boolean, the line doesn't make sense (logic error).
Use more readable variable names:
$nowPlayingName
$nowPlayingArtist
You are right, var_dump should not be there. var_dump() is used for debugging.
Following code would be enough:
if(isset($nowplayingname)) { ... }

'If' statement with the 'or' operator in PHP

I'm trying to build up a PHP if statement with or ("||") operators, but it doesn't seem to work.
$country_code = "example_country_code";
if ($country_code != 'example_country_code' || !clientIscrawler()) {
echo 'the script can be executed';
}
else {
echo 'skipping';
}
With the given example, it should be echoed skipping, but it doesn't happen like that. What am I doing wrong?
Perhaps the double negatives are giving you problems. Let's rewrite it to:
!($country_code == 'example_country_code') || !clientIscrawler()
This can be turned into an equivalent condition with &&:
!($country_code == 'example_country_code' && clientIscrawler())
By reversing the if you would get this:
if ($country_code == 'example_country_code' && clientIscrawler()) {
echo 'skipping';
} else {
echo 'the script can be executed';
}
Therefore, in your code, it will only print skipping if clientIscrawler() is truthy.
If you have multiple conditions with the OR operator, in which case you don't want the if statement to evaluate as true, the syntax is:
if(!($something == "something" || $something == 'somethingelse')){
do stuff...
}
Here is an example:
$apples = array (
1 => "Pink Lady",
2 => "Granny Smith",
3 => "Macintosh",
4 => "Breaburn"
);
foreach($apples as $apple){
// You don't want to echo out if the apple name is "Pink Lady" or "Macintosh"
if(!($apple == "Pink Lady" || $apple == "Macintosh")){
echo $apple."<br />";
}
}
// Output is:
Granny Smith
Breaburn
In your given code, it all depends on your function call
!clientIscrawler()
You will be getting the script can be executed output only when your function call returns FALSE. I think it is returning TRUE right now, which is why you are not getting the desired output.
Maybe this can help you:
if ( ($country_code != 'example_country_code') || clientIscrawler() == false) {
Try this way:
if ( ($country_code != 'example_country_code') || !clientIscrawler()) { ...

problem in Condition chaining

I am very new in php. I am having a problem in condition checking. I have the condition chain like this
if(condition1){
if (condition2){
Statement1;
}else{
Statement2;
}
else{
if (same condition2){
Statement3;
}else{
Statement4;
}
Now when I am writing this like I am having errors -
if (condition1) "AND". (condition2)
Statement1;
if (condition1) "AND". (!condition2)
Statement2;
if (!condition1) "AND". (condition2)
Statement3;
if (!condition1) "AND". (!condition2)
Statement4;
Can anyone enlighten me where I am wrong?
Here is the real code I am writing -
if (!isset($store['stationfilter'])) "AND". ($fromdate_display == $todate_display)
$storeSql_current = sprintf($sql_current, ''); //error 1
if (!isset($store['stationfilter'])) "AND". (!$fromdate_display == $todate_display) //error2
$storeSql_otherThancurrent = sprintf($sql_otherThancurrent, ''); //error3
if (isset($store['stationfilter'])) "AND". ($fromdate_display == $todate_display) //error4
$storeSql_current = sprintf($sql_current, "AND" . $store['stationfilter']); //error5
if (isset($store['stationfilter'])) "AND". (!$fromdate_display == $todate_display) //error6
$storeSql_otherThancurrent = sprintf($sql_otherThancurrent, "AND" . $store['stationfilter']); //error7
Please tell me where I am wrong.
Thanks,
Neel
You should write like this:
if ($condition1 && $condition2) ....
if ($cond1 && $cond2) {
# stmt1
} else if ($cond1) {
# stmt2
} else if ($cond2) {
# stmt3
} else {
# stmt4
}
I've amended the above with your actual conditions, below. I've also taken a guess at what your statements are supposed to look like...
if ( isset($store['stationfilter']) && $fromdate_display === $todate_display ) {
$storeSql_current = sprintf('%s AND %s', $sql_current, $store['stationfilter']);
} else if ( isset($store['stationfilter']) ) {
$storeSql_otherThancurrent = sprintf('%s AND %s', $sql_otherThancurrent, $store['stationfilter']);
} else if ( $fromdate_display === $todate_display ) {
$storeSql_current = (string) $sql_current;
} else {
$storeSql_otherThancurrent = (string) $sql_otherThancurrent;
}
If what you're doing is to build a sql statement, then this approach may be dangerous because of the potential for SQL Injection. If $store['stationfilter'], $sql_current or $sql_otherThancurrent (the data) are coming from an untrusted source (all sources are untrusted unless the source is code you have written) then you should, at minimum, be using the database adapter to quote the data or, better, using parameterised queries.

php "if" condition mystery

I am running into a funny problem with a mischievous "if" condition :
$condition1="53==56";
$condition2="53==57";
$condition3="53==58";
$condition=$condition1."||".$condition2."||".$condition3;
if($condition)
{
echo "blah";
}
else
{
echo "foo";
}
Why does the if condition pass?
Why does php echo "blah"? What do I do to make php evaluate the "if" statement and print "foo"?
The problem here is that you're putting your expressions in strings!
Your $condition1, $condition2, and $condition3 variables contain strings, and not the result of an expression, and the same goes for your $condition variable which will be a string that looks like 53==56||53==57||53==58. When PHP evaluates a string it considers it true if it is not empty and not equal to 0, so your script will output blah.
To fix this you just need to take your expressions out of the strings. It should look like this:
$condition1 = 53 == 56; // false
$condition2 = 53 == 57; // false
$condition3 = 53 == 58; // false
$condition = $condition1 || $condition2 || $condition3; // false || false || false = false
if ($condition) {
echo 'blah';
} else {
echo 'foo'; // This will be output
}
You're evaluating strings as booleans; they'll aways be true (except the strings "" and "0". Get rid of almost all of the quotes in your program.
Those aren't conditions, they're strings.
$condition1=53==56;
$condition2=53==57;
$condition3=53==58;
$condition=$condition1 || $condition2 || $condition3;
if($condition)
{
echo "blah";
}
else
{
echo "foo";
}
Because you're not checking those variables, it's saying if (String) will always return true. (unless "")
You should be doing:
if(53==56 || 53==57 || 53==58)
{
echo "blah";
}
else
{
echo "foo";
}
All $condition* variables will evaluate to true. This is how PHP sees it:
if("53==56" || "53==57" || "53==58")
What you want is this:
$condition1 = 53==56;
$condition2 = 53==57;
$condition3 = 53==58;
It's because you're evaluating a string, and strings other than empty strings evaluate to true.
You are concatting a string together, a non-empty string equals TRUE in php.
Because when the if passes, $condition is a string (a concatenation of) containing the text of your conditions. Try using if(eval($condition)).
String always evaluate to true if its not empty
And btw php make implicit conversion to boolean

Categories