I am trying to print out yes if a boolean table field from a database query is true, and no if it is false.
I am doing this:
echo "<td>"{$row['paid'] ? 'Yes' : 'No'";}</td>";
Why is this incorrect?
echo "<td>".(($row['paid']) ? 'Yes' : 'No')."</td>";
Personally, i never echo HTML so i would do this:
<td><?=(($row['paid']) ? 'Yes' : 'No')?></td>
Just a preference thing though..
echo "<td>".(($row['paid']) ? 'Yes' : 'No')."</td>";
Other guys have corrected your mistake, but I thought you might like to know why.
Your use of a ternary isn't actually the problem, it's the way you join it to the other stuff.
Echo is a function that takes one variable; a string. It's actually this (although people tend to leave the brackets off):
echo(SomeString);
In your case, SomeString needs to be "" followed by the outcome of your ternary, followed by "". That's three strings, which need to be glued together into one string so that you can "echo()" them.
This is called concatenation. In PHP, this is done using a dot:
"<td>" . (($row['paid']) ? 'Yes' : 'No') . "</td>"
Which can be placed inside an echo() like this:
echo("<td>" . (($row['paid']) ? 'Yes' : 'No') . "</td>");
Alternatively, you can skip concatenation by using a function that takes more than one string as a parameter. Sprintf() can do this for you. It takes a "format" string (which is basically a template) and as many variable strings (or numbers, whatever) as you like. Use the %s symbol to specify where it needs to insert your string.
sprintf("<td>%s</td>",(($row['paid']) ? 'Yes' : 'No'));
The world is now your oyster.
Ref this
echo "<td>".(($row['paid']) ? 'Yes' : 'No')."</td>";
Since echo takes many arguments, should use comma instead of string concatenation which takes more processing and memory:
echo "<td>", (($row['paid']) ? 'Yes' : 'No'), "</td>";
Related
I am facing one issue. I am setting boolean true/false value but when I am echo that value its showing me 1/blank using PHP. I am explaining my code below.
$qry="SELECT c.member_id,c.rest_name,c.quadrant,c.proviance,c.postal,c.address,c.country,c.city,c.person,c.mobile,c.url,c.share_url,c.premium,c.image,c.multiple_image,c.business_phone_no,c.latitude,c.longitude,q.quadrant AS quadrant_name,ct.city_name FROM db_restaurant_basic AS c LEFT JOIN db_quadrant AS q ON c.quadrant=q.quad_id LEFT JOIN db_city AS ct ON c.city=ct.city_id WHERE c.member_id='".$member_id."' and c.status=1 ORDER BY rand()";
$fetchqry=mysqli_query($connect,$qry);
if(mysqli_num_rows($fetchqry) > 0){
while($row1=mysqli_fetch_array($fetchqry)){
if($row1['multiple_image']==''){
$available_image=false;
}else{
$available_image=true;
}
}
}
echo $available_image.'<br>';
Here that echo output is given me 1/blank value . Here I need to get the true/false as output.
PHP doesn't support printing True/False, so you can use following as a work-around:
echo $available_image ? 'true' : 'false';
Or even simpler, you can use:
echo json_encode($available_image);
There is a simple explanation.
As the documentation page of echo() describes it, echo outputs one or more strings.
Since the value of $available_image is not a string but a boolean, conversion is required.
The documentation page of strings, section Converting to string explains:
A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.
This is how PHP works. Also take a look at the type comparison tables.
If you need to display true or false (as strings), all you have to do is to use $available_image as the condition into a ternary comparison operator to produce the strings you need:
echo $available_image ? 'true' : 'false';
Or, if you print the value of $available_image only for debug purposes, you can use var_dump() instead of echo(). It displays not only the value (of the expression passed to it) as string (it produces true and false for booleans) but also the type of the value.
Check the manual for casting to string. Try this:
echo $available_image ? 'true' : 'false', '<br>';
Please declare the $available_image at the top of your code and set default value TRUE/FASLE to it like follows
$available_image = FALSE;
I need to show the message "N/A" if the $row['gate'] is empty. Is it possible to do this using logical symbols ":","?" ?
Like this?
echo (isset($row['gate']) && !empty($row['gate'])) ? $row['gate'] : 'N/A';
PHP 5.3+ allows you to do this.
echo $row['gate'] ?: 'N/A';
That will essentially 'coalesce' an empty value to 'N/A' but if it has a value, it will echo the value.
Ternary operator is commonly used for this kind of validation.
Example while using phps empty()-function:
$output = (!empty($row['gate'])) ? $row['gate'] : 'N/A';
var_dump($output);
(This ofc only checks if the variable is empty, like asked. If you want to check if the variable is defined, use a isset() in there, too).
Yep, it's possible
<?php
$row = array();
echo (empty($row['gate'])) ? 'N/A' : $row['gate'];
?>
yes it is possible with ternary operator
isset($row['data']) ? "your_value" : "N/A";
This is the simplest way.
I want to evaluate a simple ternary operator inside of a string and can't seem to find the correct syntax.
My code looks like this:
foreach ($this->team_bumpbox as $index=>$member)
echo ".... class='{((1) ? abc : def)}'>....";
but I can't seem to get it to work properly. Any ideas on how to implement this?
You can't do it inside the string, per se. You need to dot-concatenate. Something like this:
echo ".... class='" . (1 ? "abc" : "def") . "'>....";
Well, you can do it actually:
$if = function($test, $true, $false)
{
return $test ? $true : $false;
};
echo "class='{$if(true, 'abc', 'def')}'";
I'll let you decide whether it is pure elegance or pure madness. However note that unlike the real conditional operator, both arguments to the function are always evaluated.
I'm new to shorthand conditional statements and I can't for the life of me work out how to do it, here's the simple code I have:
<?php
function evolve_nav($vals) {
echo '<'.$vals['type'] !== '' ? ''.$vals['type'].'' : 'darn''>';
}
?>
Does anyone know why this doesn't return anything and results in an error?
You just forgot some brackets:
function evolve_nav($vals) {
echo '<'.(!empty($vals['type']) ? $vals['type'] : 'darn').'>';
}
evolve_nav(array('type' => 'foobar'));
evolve_nav(array('not' => 'showing'));
echo '<' . ($vals['type'] !== '' ? $vals['type'] : 'darn') .'>';
$descriptiveVariableName = $vals['type']!=='' ? $vals['type'] : 'darn';
// View code
echo "<$descriptiveVariableName>";
''.$vals['type'].'' is superfluous, make it $vals['type']
'darn''>' those are two string literals without any operator (or anything) between them -> syntax error.
In this case I'd rather not use string concatenation (i.e. using the dot-operator like 'xyz' . $a ) but "pass" multiple parameters to echo.
echo
'<',
''!==$vals['type'] ? $vals['type'] : 'darn',
'>';
or using printf
printf('<%s>', ''!==$vals['type'] ? $vals['type'] : 'darn');
I am in a bind, multiple times on a page for different form items, I insert a css div class into a form item ONLY if an error_array key exists, this is how I highlight a form item that has an error in it.
Works, great if I have an error because then my error array is set, problem is before an error is set, it tries to look for an array key that does not exist. I was thinking using php's isset function first would be the ticket but I guess you cannot combine isset with another function?
<?php
//this works
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)){
echo "good";
}
// this does not work, will give write errors
$search_array = array('first' => 1, 'second' => 4);
if (isset(array_key_exists('first', $search_array))){
echo "good";
}
// Here is 1 example how I need to make the end result work
$country_class = (array_key_exists('country', $signup_errors)) ? ' signup_error' : ' signup_good';
echo '<select name="country" id="country" class="textarealong ' .$country_class. '"/>';
?>
In other parts I use it like this
<?PHP echo(array_key_exists('password', $signup_errors)) ? ' signup_error' : ' signup_good';?>
And I need to have it be a 1 line code if possible
If isset is false, the second statement wont get executed, because the parsers knows that both statements have to be true to get the whole statement true.
$country_class = ( isset($signup_errors) && array_key_exists('country', $signup_errors)) ? ' signup_error' : ' signup_good';
BUT i would suggest you to initialize every variable you are using...
I'm not familiar enough with PHP syntax, but this sounds like a job for short-circuit evaluation, i.e. || or &&, where the second term is not evaluated if the first term alone can determine the result (if it's True in || or False in &&).
This is an old question, but it's an even simpler answer. isset checks the array and the key. This works great and doesn't generate any notices if the array is not set:
if (isset($search_array['first'])){
echo "good";
}
Or:
$country_class = isset($signup_errors['country']) ? ' signup_error' : ' signup_good';