This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 9 years ago.
I am starter php developer, I know, if else, or, elseif... but I don't understand those : ? and other symbols. So can you tell me what this lines mean:
$success = $success ? $b->save(false) : $success;
if (!success) // shouldn't this be without "!"
$transaction->commit(); // this means "do the job, if ok"
else
$transaction->rollBack(); // this means "don't do the job, if not ok"
Also, can you tell me how to call this symbols, I don't know their name and so I can't find tutorials about them
It's pretty common in a lot of languages, you can find this Ternary Operations for example in javascript aswell
It is a short hand for an if/else.
The part before the ? is the condition, the next part is the code to execute if the condition returns true, and the last part (after the :) if it returns false:
condition ? if true : if false;
$a = 3 > 5 ? 'three is greater than five' : 'three is lesser than five';
In this case $a would be three is lesser than five;
I would recommend ternary operations only for very simple conditions/results, if not, you end up writting less maintainable code, sacrificing shortness for legibility
the above code looks like if $success from previous transactions was true , try $b->save(false) and then put the returned value from $b->save(false) into $success.
$b->save(false) means save without validation, and after successful save, will return true
then the if part is very clear
That's a Ternary Operator, a short form for an if statement.
$success = $success ? $b->save(false) : $success;
is the same as
if($success) {
$success = $b->save(false);
} else {
$success = $success;
}
Related
This question already has answers here:
How to validate an email address in PHP
(15 answers)
Closed 2 years ago.
I have a PHP script that runs when a form button is clicked. Everything is working fine, apart from a routine that checks for email format. I have tried using the inbuilt PHP filter function for that but it doesnt even seem to run (I am using a suitable version of PHP for this). I am checking for the existence of the 'at' symbol and a dot for the domain name, just on the dev machine WAMP webserver at the moment. If I enter an invalid address (say abc123 - i.e., no 'at' symbol, no dot) it seems to think everything is OK and loads the appropriate page. Code here: (tempvar echoes correctly by the way, and is just there for experiment)
$_SESSION['emailaddress']=$_POST['unamebox'];
$tempvar = $_SESSION['emailaddress'];
function checkEmail($tempvar) {
$find1 = strpos($tempvar, '#');
$find2 = strpos($tempvar, '.');
return ($find1 !== false && $find2 !== false && $find2 > $find1);
}
if ( checkEmail($tempvar) )
{
echo "OK";
}
else
{
echo "Bad email format!";
}
Because strpos return an integer if found the template in string otherwise return false. Now the !== operator is also match variable types!
When find1 or find2 strpos is match, the !== return false value!
Why is my ternary ignoring the first condition ($order->status === "prepairing") ?
It always skips the first condition when checking the order status and immediately goes toward the second (and always see's it as true)
$messageMiddle = ( ($order->status === "prepairing") ? " your prder is being prepared. Make your way towards the store."
: ($order->status === "complete") ?' your order is done! Please show your order-code at the store.'
: ' thank you for ordering ');
You need to group every next expression in parenthesis as follows. You forgot to enclose the second ternary expression in parentheses.
$messageMiddle = ($order->status === "prepairing") ? " your order is being prepared. Make your way towards the store." :
(($order->status === "complete") ? ' your order is done! Please show your order-code at the store.' : ' thank you for ordering ');
But you should avoid this approach anyways.
A better way to react to the status of an order would be a switch statement. Like this:
switch ($order->status) {
case "preparing" : $messageMiddle = " your order is being prepared. Make your way towards the store.";
break;
case "complete" : $messageMiddle = " your order is done! Please show your order-code at the store.";
break;
default : $messageMiddle = " thank you for ordering ";
break;
}
It is easy to see how you can extend this to react to other status words.
Note that I changed `"prepairing" to "preparing".
One of the things programmers strive for is succinct code. However, shorter code is not always better code. It might be less readable and more difficult to maintain and extend.
I have code as bellow :
number_format(($hasilz->harga>100000 ? $hasilz->harga+2000 :
($hasilz->harga>300000 ? $hasilz->harga+4000 :
($hasilz->harga>400000 ? $hasilz->harga+8000 :
$hasilz->harga+10000))), 0, ',', '.')
this code result and read +2000 and +10000 only
any idea ?
Let's see what you got there (simplified):
if (hagara > 100000) {
harga+2000
} else if (hagara > 300000) {
hagara+4000
} else if (hagara > 400000) {
hagara+8000
} else {
hagara+10000
}
If you write it like this, its easy to see. hagara is either >100000 which results in +2000 or it is less, then it results in +10000.
In other words, the two else if will never be true, because if they were, the first if would already be true.
I think this is also a good example, when you should NOT use the tenary operator. It just makes it really hard to read and understand... sometimes the good old it-approach ist just the better solution. ;)
EDIT: To answer the question, you have to use a different order of the if-statements, beginning with the biggest one (or write them completely different). However, as already mentioned, you shouldn't do that.
<?php echo isset($areas['footer']) ? $areas['footer'] : null; ?>
Any way to improve that?
Note that you are echoing and in false condition it would be null which does not have any effect. You could say like 'empty' or ' ' or 'not found' instead. Other alternative is to get the return value of isset:
$return = isset($areas['footer']) ? $areas['footer'] : null;
if ($return)
{
// $return contains footer info
}
else
{
// footer was not set :(
}
Depending on where $areas comes from it might be cleaner to assign it to a variable:
$footer = isset($areas['footer']) ? $areas['footer'] : null;
Then you can use $footer without any additional isset checks.
You can also spare the else branch, by setting a default:
$footer = null;
if (isset($areas['footer'])) {
$footer = $areas['footer'];
}
echo $footer;
No, this is the most concise way of handling this sort of output.
"i'm using this kind of code very often"
Maybe you should avoid the issue altogether by using a template language, or encapsulating this behavior in a function?
like this:
function get_area($area) {
if... //your code
return $area
One shorter version i can think of would be:
<?php !isset($areas['footer']) or print $areas['footer']; ?>
But i'm not sure if it is faster or more elegant.
What do you guys think?
echo $areas['footer'];
Simple and has the exact same effect as the original line.
Edit in reply to Felix
This gives a notice, but unless you're supposed to turn this in as ultra-perfect homework, it doesn't really matter. You can either fill your code with isset calls or ignore small stuff like this. I'd worry about it if I was working in say... Java, but pragmatically nobody is going to care if PHP code that works produces notices.
I am trying to insert messages to a function
function addMessage($item) {
if ($result) {
$message = '<p class="ok">
<span> Item added </span>
</p>
';
header("Refresh: 2; url=?page=$item");
}
else{
$message = '<p class=not><span>There is an error blah blah</span></p>';
}
return $message;
}
When I use it : addMessage('contents') it only returns to second condition. How can I fix this?
You are checking $result inside the if but its neither been assigned any value before that nor been declared as global . I think you meant to check $item:
if ($item) {
Hi jasmine
Your function always returns the second condition because you haven't assigned a value to $result, eider inside the function or when you call the function (like unicornaddict mentioned by other words).
To get your code working the way you probably want, your function should be like this:
function addMessage($item, $result) {
if ($result) { // It will return this condition, case $result has any value assigned and is different from FALSE (boolean)
$message = '<p class="ok">
<span> Item added </span>
</p>
';
header("Refresh: 2; url=?page=$item");
}
else{ // It will return this condition, case $result doesn't has any value assigned or is equal to FALSE (boolean)
$message = '<p class="not"><span>There is an error blah blah</span></p>';
}
return $message;
}
And then you can call the function like you where already calling it, but don't forget to include a variable or a value that should be handled as the $result variable inside the function
addMessage('contents', $result);
Note:
In your $message variable you have <p class=not> and should be <p class="not">.
Remember that header() must be called before any actual output is sent to the browser.
Hope it Helps.
Is $result defined in your script? Use if ($item) instead.
Be very careful that PHP allows the usage of undefined variables.
what they said :-)
Btw, a decent IDE (like Zend) will analyze your code and warn you about things like that.
Such static code analysis is known as "linting", so google for "PHP lint" or see questions like Is there a static code analyzer [like Lint] for PHP files?
But this code sample is so small that I guess you are a beginner (no offence interned - we all had to start somewhere), so do a lot of reading and gather a lot of tools and experience.
For instance, a decent IDE (like Zend or Eclipse PDT) would let you step through your code, line nby line, and examine the value of each variable and then you ought to have seen the problem.
Welcome to PHP and good luck!