I keep getting an error with the following bit of code. It is probably some small thing but I don't see what is wrong.
while($row = mysql_fetch_array($result))
{
$varp = $row['ustk_retail'];
if ($varp<80000) { $o1 = 1; }
if (($varp=>80000) && ($varp<100000)) { $o2 = "1"; }
if (($varp=>100000) && ($varp<120000)) { $o3 = "1"; }
if (($varp=>120000) && ($varp<140000)) { $o4 = "1"; }
if (($varp=>140000) && ($varp<160000)) { $o5 = "1"; }
if (($varp=>160000) && ($varp<180000)) { $o6 = "1"; }
if (($varp=>180000) && ($varp<200000)) { $o7 = "1"; }
if (($varp=>200000) && ($varp<220000)) { $o8 = "1"; }
if (($varp=>220000) && ($varp<240000)) { $o9 = "1"; }
if (($varp=>240000) && ($varp<260000)) { $o10 = "1"; }
if (($varp=>260000) && ($varp<280000)) { $o11 = "1"; }
if (($varp=>280000) && ($varp<300000)) { $o12 = "1"; }
if ($varp>=300000) { $o13 = "1"; }
}
Running php -l (lint) on your code I get a
Parse error: syntax error, unexpected T_DOUBLE_ARROW
The T_DOUBLE_ARROW token is what PHP expects when assigning array values to array keys.
When comparing for Greater than or equal to the PHP Parser expects T_IS_GREATER_OR_EQUAL, meaning you have to use >= instead of =>.
See
the chapter on Comparison Operators in the PHP Manual and
the List of Parser Tokens in the PHP Manual
Greater than or equal to is >= sign, not =>
Update:
You are right. It's small but hard to find mistake.
It took me to split whole line into pieces to see where the problem is:
<?php
if
(
$varp
=>
80000
)
So, it says parse error on line 5 and I had to doublecheck this operator.
Of course, at first I separated the problem line from the rest of the code to be certain.
You have an expression error.
$varp=>220000 // is not a valid php expression
=> operator is used to assign values in arrays like:
$x = array( 'foo' => 'bar');
>= is the comparation assigment greater than or equal
You have made a mistake in the if conditions. The greater than Equal to sign is >= and not =>.
The answer has already been given but thought this was neat enough to share:
PHP accepts boolean expressions in it's switch statement.
switch(TRUE) {
case $range <= 10: echo "range below or equal to 10"; break;
case $range <= 20: echo "range above 10 below or equal to 20"; break;
case $range <= 30: echo "range above 20 below or equal to 30"; break;
default: echo "high range";
}
In my opinion this generates the cleanest most readable code.
This is more readable and compact way to do the same:
$ranges = range(300000, 80000, -20000);
$index = 1;
$varp = 220001;
foreach ($ranges as $i => $range) {
if ($varp >= $range) {
$index = 13 - $i;
break;
}
}
${'o' . $index} = 1;
Anyway - I think you're doing something wrong with using variable name of result.
You probably want to change ($varp=300000) to ($varp==300000) and it might help to enclose the full if-statement inside (), like this
if($varp80000 && $varp100000 && $varp120000 && $varp140000 && $varp160000 && $varp180000 && $varp200000 && $varp220000 && $varp240000 && $varp260000 && $varp280000 && $varp==300000) { $o13 = "1"; }
On another note, where to these strange $varp#### variables come from?
Not sure whether the code you've posted has gotten messed up somehow, but it looks like you're missing "==" in some of the if conditions. Also, as Skilldrick pointed out, the whole if condition should be in parentheses
"Greater than or equal to is >= NOT =>. You use => for arrays for keys/values.
Add one more bracket around the conditions in if....
if ( ($varp80000) && ($varp100000) && ($varp120000) && ($varp140000) && ($varp160000) && ($varp180000) && ($varp200000) && ($varp220000) && ($varp240000) && ($varp260000) && ($varp280000) && ($varp=300000) ) { $o13 = "1"; }
Related
I am sorry to ask such a question but am bit confused about this.
I am having simple variables defined.
$a =1;
$b=2;
$c=3;
$d="";
for($i=0;$i<10;$i++)
{
$testa = 1;
$testb = 4;
$testc = 3;
$testd = 7;
if($a!="" || $b!="" || $c!="" || $d!="") {
if($a==$testa && $b==$testb && $c==$testc && $d==$testd) {
echo $testa;
echo $testb;
echo $testc;
echo $testd;
}
}
}
This is sample php code.
what I need is that I have variables defined at top. SO in my loop i want to display result if user has any 1 variable but in below loop display result based on "and" parameter.
I actually want to skip the empty variable. SO in this case, I want as $d is empty, so it should be prevented somehow from if($a==$testa && $b==$testb && $c==$testc && $d==$testd) from here.
Any help is really appreciated.
To skip the empty values from the check, use ||
if ( ... && (empty($d) || $d == $testd)) {
Then if you also want to skip it in your echos :
echo !empty($d) ? $testd : '';
I have string $a,$b,$c
I know if all of them not null express in this way:
if($a!="" && $b!="" && $c!="")
But if either 2 of them not null then go into the true caluse
if($a!="" && $b!="" && $c!=""){
** do the things here **
}else if(either 2 are not null){
**do another things here**
}
How to express it?
I would write a simple function like this to check:
function checkInput($var)
{
$nulls=0;
foreach($var as $val)
{
if(empty($val))
{
$nulls++;
}
}
return $nulls;
}
Then access it like this:
$inputs=array($a, $b, $c.... $z);
$nullCount=checkInput($inputs);
if($nullCount==0)
{
// All nulls
}
if($nullCount>2)
{
// More than 2 nulls
}
or for an one-off test, just pop the function into the actual if statement like this:
if(checkInput($inputs)>2)
{
// More than 2 nulls...
}
etc etc. You can then use the one function to check for any number of nulls in any number of variables without doing much work - not to mention change it without having to rewrite a long if statement if you want to modify it.
Other answers are good, but you can expand this to easily handle more variables:
$variables = array($a, $b, $c, $d, ....);
$howManyNulls = 0;
foreach($variables as $v){
if($v == ''){
$howManyNulls++;
}
}
if($howManyNulls == count($variables) - 2){
// do stuff
}
you can try this
if($a!="" && $b!="" && $c!="")
{
** do the things here **
}
else if(($a!="" && $b!="") || ($b!="" && $c!="") || ($a!="" && $c!=""))
{
**do another things here**
}
Try:
if($a!="" && $b!="" && $c!=""){
** do the things here **
}else if(($a!="" && $b!="") || ($a!="" && $c!="") || ($b!="" && $c!="")){
**do another things here**
}
$var[] = empty($a) ? 0:$a;
$var[] = empty($b) ? 0:$b;
$var[] = empty($c) ? 0:$c;
$varm = array_count_values($var);
if ($varm[0] === 0) {
//Code for when all aren't empty!
} elseif ($varm[0] === 1) {
//Code for when two aren't empty!
}
N.B; You may need to replace the 0 for a string/integer that will never crop up, if your variables are always strings or empty then 0 will do for this. The method for using bools within this would require more code.
$nullCount = 0
if($a!=""){ ++$nullCount; }
if($b!=""){ ++$nullCount; }
if($c!=""){ ++$nullCount; }
if($nullCount == 3){ // all are null
// do smth
}else if($nullCount == 2){ // only two are null
// do other
}
Just for fun, here's something potentially maintainable, should the list of arguments increase:
function countGoodValues(...$values) {
$count = 0;
foreach($values as $value) {
if($value != "") {
++$count;
}
}
return $count;
}
$goodValues = countGoodValues($a, $b, $c); // Or more... or less
if($goodValues == 3) {
// Do something here
}
else if($goodValues == 2) {
// And something else
}
Reference for the ... construct (examples #7 and #8 in particular) are available on php.net.
You can use double typecasting (to boolean, then to number) in conjunction with summing:
$count = (bool)$a + (bool)$b + (bool)$c;
if ($count == 3)
// ** do the things here **
else if ($count == 2)
//**do another things here**
There is also possible such solution:
<?php
$a= 'd';
$b = 'a';
$c = '';
$arr = array( (int) ($a!=""), (int) ($b!=""), (int) ($c!=""));
$occ = array_count_values($arr);
if ($occ[1] == 3) {
echo "first";
}
else if($occ[1] == 2) {
echo "second";
}
If you have 3 variables as in your example you can probably use simple comparisons, but if you have 4 or more variables you would get too big condition that couldn't be read.
if (($a!="") + ($b!="") + ($c!="") == 2) {
// two of the variables are not empty
}
The expression a!="" should return true (which is 1 as an integer) when the string is not empty. When you sum whether each of the strings meets this condition, you get the number of non-empty strings.
if (count(array_filter([$a, $b, $c])) >= 2) ...
This is true if at least two of the variables are truthy. That means $var == true is true, which may be slightly different than $var != "". If you require != "", write it as test:
if (count(array_filter([$a, $b, $c], function ($var) { return $var != ""; })) >= 2) ...
if($a!="" && $b!="" && $c!="") {
echo "All notnull";
} elseif(($a!="" && $b!="") || ($b!="" && $c!="") || ($a!="" && $c!="")) {
echo "Either 2 notnull";
}
Not sure how to use the eval() I thought I read the documentation correctly and am trying to do this (I know the logic is awful, but I was just trying it out).
if($showUnlisted){
$unlistedIfStatement = '!$price || $car["sale_price"] == 0 ||($priceFrom <= $car["sale_price"] && $priceTo >= $car["sale_price"])';
}
else{
$unlistedIfStatement = '!$price ||($priceFrom <= $car["sale_price"] && $priceTo >= $car["sale_price"])';
}
if(eval($unlistedIfStatement)){
//DO SOME STUFF
}
I get this error:
Parse error: syntax error, unexpected end of file
Looking at these examples(http://us1.php.net/eval) it should run whatever is in the string as a line of code. Also this definition "The eval() function evaluates a string as PHP code." from http://www.w3schools.com/php/func_misc_eval.asp Basically, I'm trying to store a line of code in a variable and have it run like I would do in JavaScript. Very new to PHP, I'm sorry if my question is dumb.
EDIT:
I've read the many posts as to why the eval() is a bad tool, I honestly am just asking out of curiosity.
EDIT2:
meagar's code worked splendidly, the only thing I had to do to get it to work was add semi-colons before the string ended. I went to edit his post, but my edit was denied. Here is the code that worked for me....Obviously I'll be changing it to something that my peers will not poke fun at.
if($showUnlisted){
$unlistedIfStatement = 'return !$price || $car["sale_price"] == 0 ||($priceFrom <= $car["sale_price"] && $priceTo >= $car["sale_price"]);';
}
else{
$unlistedIfStatement = 'return !$price ||($priceFrom <= $car["sale_price"] && $priceTo >= $car["sale_price"]);';
}
if(eval($unlistedIfStatement)){
//DO SOME STUFF
}
The documentation that you linked to is very clear:
eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned.
Each of your eval'd lines must return a value, or they evaluate to null:
if($showUnlisted){
$unlistedIfStatement = 'return !$price || $car["sale_price"] == 0 ||($priceFrom <= $car["sale_price"] && $priceTo >= $car["sale_price"])';
}
else{
$unlistedIfStatement = 'return !$price ||($priceFrom <= $car["sale_price"] && $priceTo >= $car["sale_price"])';
}
if(eval($unlistedIfStatement)){
//DO SOME STUFF
}
As indicated in another answer, eval() returns null in absence of a return value. However, what you're actually looking for is a callback:
Somewhere in your code:
function showUnlisted() {
return !$price || $car["sale_price"] == 0 || ($priceFrom <= $car["sale_price"] && $priceTo >= $car["sale_price"]);
}
function dontShowUnlisted() {
return !$price ||($priceFrom <= $car["sale_price"] && $priceTo >= $car["sale_price"]);
}
Then, where you need to decide between these functions:
if ($showUnlisted) {
$appropriateFunction = 'showUnlisted';
} else {
$appropriateFunction = 'dontShowUnlisted';
}
if (call_user_func($appropriateFunction)) {
//do stuff
}
This prevents you from falling prey to the evils of eval, lets you test those functions, utilize IDEs more effectively, and predict the outcome better. Passing functions as objects is a useful thing, and while awkward in PHP, a common practice in more modern languages (Scala, C#, etc.).
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)) { ... }
I have three variables which determine an outcome. There is only two outcomes but the outcome is based on the variables. I have thought up some long if statements but I am wondering if there is a cleaner way to do it.
$loggedin = (0 or 1) // If it is 0 then one outcome if 1 then it falls onto the next three variables
$status = (0-5) // 4 dead ends
$access = (0-3) //
$permission = (0-9)
Different combinations of the last two variables result in different outcomes, although some combinations are irrelevant as they are dead ends.
if ($loggedin == 1 && ($status == 1 || $status == 2 ) && 'whattodohere' ):
I could type all of the combinations manually ($access == 0 && ($var == 2 || $var = 6)) but I am wondering if there is a better way of doing this that I am unaware of.
Have a look at bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) - http://php.net/manual/en/function.in-array.php
Also take a look at range(...) - http://php.net/manual/en/function.range.php
$status == 1 || $status == 2 [... $status == n] can be reduced to in_array( $status, range(0, $n) )
Using in_array & range is more costly performance-wise tho, so if you're dead sure you only need to try against 2 different values, use == operator instead.
An approach could to be to use switch(): http://php.net/manual/en/control-structures.switch.php
Example:
<?php
/*
$loggedin = (0 or 1) // If it is 0 then one outcome if 1 then it falls onto the next three variables
$status = (0-5) // 4 dead ends
$access = (0-3) //
$permission = (0-9) */
$access = 1;
$loggedin = 1;
$status = 1;
if ($loggedin == 1) {
if ($status == 1 || $status == 2 ) {
switch($access) {
case 0:
//do some coding
break;
case 1:
echo 'ACCESSS 1';
//do some coding
break;
default:
//Do some coding here when $access is issued in the cases above
break;
}
}
}
else {
//Do coding when $loggedIn = 0
}
?>
In the example ACCESS 1 would be the output.
Maybe you could also do some math and compare the result (in some circumstances depending on what you want to achieve). For example:
<?php
$permission = 1;
$access = 2;
$result = $permission * $access;
if ($result > 0) {
switch($result) {
case 0:
//do something
break;
case 1:
//do something
break;
default:
//Do something when value of $result not issued in the cases above
}
}
?>