如果$ value是真实的,则返回$ value,否则返回其他内容[关闭]

I know you can to this

$var = mysql_query("SELECT * FROM..") ? mysql_query("SELECT * FROM.."):'Nope!';

// the same as this

if(mysql_query("SELECT * FROM..")) $var = mysql_query("SELECT * FROM..");
else $var = 'Nope!';

But it's inconvenient, because what if it was a function that either returned an array or false and maybe updated some data in a table. So I wondered if there is any way to do

$var = mysql_query("SELECT * FROM..") ? $returnOfFunction:'Nope!';

Something like this

$var = mysql_query("SELECT * FROM..") || 'Nope!';

But in php, that means if this is true or this is true, then i am true

I hope someone can understand my thoughts.

EDIT: Would this work?

function pickTrue($one, $two) {
  if($one == true) return $one;
  else return $two;
}

$var = pickTrue(mysql_query("SELECT * FROM table"), 'Nope');

You want the ternary-without-the-middle-part, available since PHP 5.3.

Do not write your code like this. The result from mysql_query will not always be a Boolean value that can be compared. You are also going to lose any error messages and error handling that can be performed when querying the database.

Short answer: Yes. Long Answer: Don't

Use the or operator, instead of ||. it has a lower binding preference. e.g.

$result = mysql_query($sql) || die(mysql_error()); // always kills the script
v.s.
$result = mysql_query($sql) or die(mysql_error()); // kills the script ONLY if the query returns false

However, don't use such convoluted code. Reducing line count is a fine thing, but when it makes readability suffer, it's a horribly bad thing.

The main problem is that a SELECT query either returns a boolean false (query/db failure), or a result set. You cannot know what the result set is until you actually retrieve a row of data and examin it. e.g. Just because a query call returned a non-false value, doesn't mean the query actually suceeded. A query which returns no data is still a valid query.

e.g. consider a login system, and you're checking if an account exists:

$sql = "SELECT id FROM users WHERE username=Some_username_that_doesnt_exist";
$exists = mysql_query($sql) or "Nope!";

The query is perfectly valid, but since the username doesn't exist, will return an empty result set. That's a non-false result, so the or Nope doesn't trigger. Now the code thinks the username exists, and poof... off you go on an incorrect code path.

  • First, don't use mysql_* functions. They're being deprecated.
  • Second, mysql_query returns a resource which you have to fetch from. Having one variable contain either a resource or a string is bad practice.

Here's a better way:

$q= 'SELECT a, b, c FROM mytable';
if($r= $db->query($q)){
  $success = 'yep';
  while($row = $r->fetch_assoc()) {
    //do stuff
  }
} else {
  $success = 'nope';
}