Jump to content

using or and other php shortcuts


mbeals

Recommended Posts

what are the syntax and limitations for the 'or' function?  I can't find it in the manual (try searching for "or" and see how many random sites you get).

 

I'm familiar with using it in mysql queries, like:

 

mysql_query or die(mysql_error());

 

but would like to use it more like you can in perl....

 

<?php

function test($foo = NULL){
      $var = $foo or return 0;
  return $var;
}

if($val = test(4)) echo $val;
?>

or more usefull:

<?php

function query($query){

$result =  mysql_query($query) or return 0;

        while($row = mysql_fetch_assoc($result)){
                     $data[] = $row;
          }

       return $data;
}

?>

 

but alas, php pukes.  I could use standard conditionals with mysql_errno but why use 3 lines of code when you can do it in 1?

 

 

 

So... can or be manipulated to function like that or is that just something php won't do?  Any other perl-like shortcuts in php?

Link to comment
https://forums.phpfreaks.com/topic/117555-using-or-and-other-php-shortcuts/
Share on other sites

The or operator pretty much works like this:

 

foo() or bar();

 

 

If foo returns false, call bar(). foo() and bar() can be any function ( NOT constructs... ie echo and return )

 

Your best bet is to simply use

 

if ( ($result = mysql_query($query)) == FALSE ) return FALSE;

that's kind of ugly and convoluted though...

 

I also like to try and avoid that (except for handling simple form requests), for visibility while debugging reasons.

 

i could also do:

 

if(mysql_error()) return 0;

 

but I was hoping for an elegantly simple one-liner

 

oh well

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.