I have an array. Consider that $a['info'] == 5. So I can write :
<?php echo $a['info'] . ' children'; ?> to get : "5 children".
Normally, i could write
<?php echo (isset($a['info']) ? $a['info'] : '0') . ' children'; ?>
to get "0 children" if $a['info'] == 0 or is not set. But
<?php echo ($a['info'] | '0') . ' children'; ?> works too, but I don't know why.
Thank you very much.
EDIT : works too with $a['info'] ?: '0'.
Pipe is byte or operation, so
$val | 0
Equals to
$val ? $val : 0
But this code dont check if variable exists, so if it's not - NOTICE will be raised, but code will work too, becose PHP boolean cast specifications.
isset checks if variable exists, if it exits, even if it value is 0, isset return true, so code
echo (isset($a['info']) ? $a['info'] : '0') . ' children';
echo "0 children" if variable not exits, not if it value is 0.
echo ($a['info'] | '0')
This is nothing but an OR operation , it will OR like this , 0 OR 0 = 0 , 5 OR 0 = 5 , so you will get the right answer .
A single pipe is nothing but OR operation .
Bitwise OR
Related
I am confused with basic true / false declaration results in PHP code in two different situations. Lets assume that strlen($item["description"]) = 50. I want to add "..." if the description is longer than 20 characters.
Case 1:
$art = strlen($item["description"]) > 20 ? $item["description"] : substr($item["description"], 0, 20) . "...";
echo $art;
Case 2:
$cut = strlen($item["description"]) < 20 ? $item["description"] : substr($item["description"], 0, 20) . "...";
$art = $cut;
echo $art;
My question is: Why I have to change the "<" operator in Case 1 to ">", if I want to add "..." for bigger than 20 char desc.? In Case 2 everything works fine (the first statement is true and the second false).
Thanks for help!
This works like this
$var = condition ? true returns : false returns
So in your case1 you have the following code
$art = strlen($item["description"]) > 20 ? $item["description"] : substr($item["description"], 0, 20) . "...";
echo $art;
You are saying in this code that if it's bigger than 20 return your text else return the substring + "..."
Instead of changing the "<" or ">" change the returns like this
$art = strlen($item["description"]) > 20 ? substr($item["description"], 0, 20) . "..." : $item["description"] ;
echo $art;
In the second case
$cut = strlen($item["description"]) < 20 ? $item["description"] : substr($item["description"], 0, 20) . "...";
It's like
if(strlen($item["description"]) < 20)
{
return $item["description"];
}
else
{
return substr($item["description"], 0, 20) . "...";
}
Your code reads (1), if the string is greater than 20 characters, echo the string else echo the truncated string, with the elipsis.
Whereas the logic should read something like, if the string length is greater than 20 characters echo the truncated version else echo as is.
<?php
function truncate($str) {
return strlen($str) > 20
? substr($str, 0, 20) . "..."
: $str;
}
foreach(
[
'Who are you?',
'Sometimes it\'s harder to look than to leap.'
]
as
$text
)
echo truncate($text) , "\n";
Output:
Who are you?
Sometimes it's harde...
Your second case reads fine, if the string is less than 20 chars, assign the string as is, else truncate it with the elipsis.
The ternary operator is useful shorthand for an if, else statement.
I am new to PHP and I am struggling to see why my code is not working when the echo displays 0. The code works for everything else however whenever the random operator chooses 0 it outputs 0 Negative, when I have it to display as Zero. I have no idea why it is doing this and I would appreciate any guidance.
$randomNumber = rand(-5, 5);
$var = $randomNumber;
echo $randomNumber;
echo $integerValue = (($var === 0) ? " Zero" : ($var <=-1) ? " Negative" : (($var >=1) ? " Positive" : " Not Positive or Zero") );
The problem is due to PHP ternary operator precedence, which works backwards compared to most other languages:
Understanding nested PHP ternary operator
Try this last line:
echo $integerValue = (($var === 0) ? " Zero" : (($var <=-1)
? " Negative" : (($var >=1)
? " Positive" : " Not Positive or Zero") ));
You are missing a parentheses:
<?php
$randomNumber = rand(-5, 5);
$var = $randomNumber;
echo $randomNumber;
echo $integerValue = (($var === 0) ? " Zero" : (($var <=-1) ? " Negative" : (($var >=1) ? " Positive" : " Not Positive or Zero") ) );
Explanation:
(
($var === 0) ? " Zero" : (
($var <=-1) ? " Negative" : (
($var >=1) ? " Positive" : " Not Positive or Zero"
)
)
)
You don't want to echo the assignment. You need to assign the value, then echo it. Try changing the last line to
$integerValue = (($var === 0) ? " Zero" : ($var <=-1) ? " Negative" : (($var >=1) ? " Positive" : " Not Positive or Zero") );
and then adding the line
echo $integerValue;
You already have another answer that explains why you weren't getting the outcome you expected, but just FYI, your multiple ternary expression can be simplified somewhat.
echo $var ? $var > 0 ? ' Positive' : ' Negative' : ' Zero';
$var will evaluate to false if it is zero so there's no need to explicitly compare it to zero, and the final "Not Positive or Zero" isn't really a possible outcome, as the result of rand will be an integer, which is either positive, negative, or zero by definition.
Parentheses aren't necessary, but they may make it more obvious what the expression is doing.
echo $var ? ($var > 0 ? ' Positive' : ' Negative') : ' Zero';
My validation is failing at my 'else if' statement. I have a string value of "24" for my variable $_SESSION_PLAN_ID (post data) and trying to compare it with value of $plancompare which 9 (not a string/DB data).
24 is greater than > 9
But my debug output echo 'burrp 3'; is never hit.
var_dump($_SESSION['SESS_PLAN_ID']);
echo "</br>";
if(!empty($_SESSION['SESS_PLAN_ID'])){
echo 'burrrp 1';
if($_SESSION['SESS_PLAN_ID'] >= 20 || $plancompare >= 20){
echo 'burrrp 2';
$_SESSION['SESS_DNSSEC'] = 1;
}else if($_SESSION['SESS_PLAN_ID'] > $plancompare){
echo 'burrrp 3';
echo '<br>';
$_SESSION['SESS_PLAN_BUY_CODE'] = $_SESSION['SESS_PLAN_ID'];
}
}
$_SESSION['SESS_PLAN_ID'] = $plancompare;
var_dump($_SESSION['SESS_PLAN_ID']);
echo "</br>";
var_dump($_SESSION['SESS_PLAN_BUY_CODE']);
echo "</br>";
var_dump($_SESSION['SESS_DNSSEC']);
session_write_close();
var_dump() output:
string(2) "24"
burrrp 1burrrp 2int(9)
int(0)
int(1)
How do I validate a string 24 to be greater than a int 9?
Change your condition like below, you need to do compression between similar datatypes:-
if((int)$_SESSION['SESS_PLAN_ID'] >= 20 || $plancompare >= 20){
echo 'burrrp 2';
$_SESSION['SESS_DNSSEC'] = 1;
}else if((int)$_SESSION['SESS_PLAN_ID'] > $plancompare){
echo 'burrrp 3';
echo '<br>';
$_SESSION['SESS_PLAN_BUY_CODE'] = $_SESSION['SESS_PLAN_ID'];
}
Note:- change bothe variable value into integer and then compare. Thanks.
PHP will automatically convert a numeric string into an integer for comparison, there's no need to separately type-cast them. Your code never gets to the third burp simply because your first condition always validates, because 24 will always be larger than 20 -- $_SESSION['SESS_PLAN_ID'] >= 20 -- and therefore the else part is never evaluated. Also, your first if condition is || meaning OR, so if the first part is true, it doesn't matter if the second part is true or not. Use && if both need to be true.
Another issue you probably have results from the line $_SESSION['SESS_PLAN_ID'] = $plancompare;, unless you're resetting your session between your debuggings. If you set them to the same value, then $_SESSION['SESS_PLAN_ID'] > $plancompare will always be false, because 9 > 9 == false.
I'd like to to some thing similar to JavaScript's
var foo = true;
foo && doSometing();
but this doesn't seem to work in PHP.
I'm trying to add a class to a label if a condition is met and I'd prefer to keep the embedded PHP down to a minimum for the sake of readability.
So far I've got:
<?php $redText='redtext ';?>
<label class="<?php if ($requestVars->_name=='')echo $redText;?>labellong">_name*</label>
<input name="_name" value="<?php echo $requestVars->_name; ?>"/>
but even then the IDE is complaining that I have an if statement without braces.
use the ternary operator ?:
change this
<?php if ($requestVars->_name == '') echo $redText; ?>
with
<?php echo ($requestVars->_name == '') ? $redText : ''; ?>
In short
// (Condition)?(thing's to do if condition true):(thing's to do if condition false);
You can use Ternary operator logic
Ternary operator logic is the process of using "(condition)? (true return value) : (false return value)" statements to shorten your if/else structures. i.e
/* most basic usage */
$var = 5;
$var_is_greater_than_two = ($var > 2 ? true : false); // returns true
Something like this?
($var > 2 ? echo "greater" : echo "smaller")
I like to use the minimalist PHP text output syntax:
HTML stuff <?= $some_string ?> HTML stuff
(This works the same as using an <?php echo $some_string; ?>)
You can also use the ternary operator:
//(condition) ? (do_something_when_true) : (do_something_when_false);
($my_var == true) ? "It's true" : "It's false ;
Ending up like this:
<?= ($requestVars->_name=='') ? $redText : '' ?>
Sample Usage
Here are a couple more uses of ternary operators, ranging from simple to advanced:
Basic Usage:
$message = 'Hello '.($user->is_logged_in() ? $user->get('first_name') : 'Guest');
Short hand Usage:
$message = 'Hello '.($user->get('first_name') ?: 'Guest');
Echo Inline
echo 'Based on your score, you are a ',($score > 10 ? 'genius' : 'nobody');
A bit Tougher
$score = 10;
$age = 20;
echo 'Taking into account your age and score, you are: ',($age > 10 ? ($score < 80 ? 'behind' : 'above average') : ($score < 50 ? 'behind' : 'above average')); // returns 'You are behind'
complicated level
$days = ($month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year %400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31)); //returns days in the given month
To learn more about ternary operators and usage, visit PHP.net Comparison Operators or here.
Use ternary operator:
echo (($test == '') ? $redText : '');
echo $test == '' ? $redText : ''; //removed parenthesis
But in this case you can't use shorter reversed version because it will return bool(true) in first condition.
echo (($test != '') ?: $redText); //this will not work properly for this case
Ill provide with an other answer since the original question specifies the use of if() in html
<a class="menu-item" href="/about-us"><?= (pll_current_language() == 'en') ? 'About us' : 'Om oss' ?></a>
The provided answers are the best solution in your case, and they are what I do as well, but if your text is printed by a function or class method you could do the same as in Javascript as well
function hello(){
echo 'HELLO';
}
$print = true;
$print && hello();
In order to fill a tab with lots of values, I would like not to display values which are equal to '0'.
For example, instead of having :
Test USER 1 0 1 0
Sample USER 1 0 1 0
I'd like to have :
Test USER 1 1
Sample USER 1 1
I display my values using printf("<td>%d</td>", $value);
I've even tried printf("<td>%0d</td>", $dl_ends[0]);
Thanks
<td><?php $value ? printf("%d", $value) : ''; ?></td>
There are two ways to solve my problem :
printf("<td>%s</td>", $value != 0 ? $value : ''); which avoid number formatting, or
$value != 0 ? printf("<td>%d</td>", $value) : printf("<td></td>"); which is longer but more precise.
Try this
printf("<td>%d</td>", $value != 0 ? $value : '');
EDIT
If you also need to catch empty strings, you can use the following code
printf("<td>%d</td>", $value != 0 && $value != '' ? $value : '');