Way to slim down this if..else statement even more? - php

$specify_step = ($_GET['specify_step']) ? $_GET['specify_step'] : getNextStep($returnId,$type);
Given the above statement, is there a way to shorthand this if statement even more so that I don't have to say $_GET['specify_step'] twice?
In the cases when I'm accessing GET or COOKIES etc, it always seems redundant and "wordier" then it needs to be.

I don't think it gets much more compact than that. My only thought is to make a temporary variable to hold $_GET['specify_step'], but that doesn't seem any shorter.

$specify_step = ($_GET['specify_step']) ?: getNextStep($returnId,$type);
It made enough logical sense to me that I had to go look it up....and according to php.net, it works in PHP 5.3. If you're using 5.3, you're in luck.

As I mentioned in a comment to your question, I don't know PHP.
Check if this works. In most langauages, if the first part is true, the function getNextStep won't be called.
$specify_step = ($_GET['specify_step']) || getNextStep($returnId,$type);

There would be this alternate boolean evaluation approach, but it just goes to show that you have to duplicate something:
$specify_step = $_GET['specify_step']
or
$specify_step = getNextStep($returnId,$type);
(Also works without decorative linebreaks.)
With PHP 5.3 you might of course use the ?: shortcut. If that's available.
Personally I can alternate to $_GET->default('specify_step', 123) for such cases.

Related

Coding Style: function calls inside statements

Ok, first of all, i suspect this is going to be closed.
Right, i have a question relating to using function calls inside statements as opposed to assigning to a variable first.
For example:
(code is in php, but question applies generally. Also, code is overly simplified)
if (myAmazingFunction() === true) {
// do something amazing
}
instead of
$amazingresult = myAmazingFuncton();
if ($amazingResult === true) {
// do something amazing
}
The question is:
Is there any performance, or other underlying pros or cons to each approach
Stylistically, is any of the approaches considered better than the other
In most languages, there will be no performance difference. In the first case, the compiler will allocate storage for the result of the function call before checking whether it is true. In the second case you're simply making this explicit.
If you are debugging, sometimes the second form is easier, as you can set a breakpoint on the second line and check the value returned by the function before the comparison is made - but then you see the result of the function by the path the executing code takes anyway in the example you've given. You can also re-use the value without rerunning the function, as Zac says in his comment.
Stylistically, this is going to be largely subjective. The only thing I'd say here is that if your variable name makes the purpose of the function output clear, then you might be adding something to the ability for others to understand your code easily.
#DavidM's answer is correct. However, I'd just like to add that stylistically, I think it depends on the name of the function and its context.
Example:
if ($food->tastesGood()) {
echo 'Mmmm!';
}
// vs.
$foodTastesGood = $food->tastesGood();
if ($foodTastesGood) {
echo 'Mmmm!';
}
In this case, it's very clear that the return value of the method tastesGood() is going to be a boolean from both the name of the method and its context. Using a temporary variable adds nothing to your code except making it redundant and less-readable at a glance. In addition, if the variable is not defined right before its used, then you have to go find the definition to understand the condition. In these cases, I would say use of a variable is worse.
Another example:
if ($dishes->wash() !== FALSE) {
echo 'Sparkly!';
}
// vs.
$dishesAreClean = $dishes->wash() !== FALSE;
if ($dishesAreClean) {
echo 'Sparkly!';
}
In this case, we can't really infer the return type of the wash() method from its name, and indeed, it would seem that it returns nothing on success and FALSE on errors. Checking if the dishes are clean then requires us to make sure that there were no errors, but the first case doesn't make for particularly readable or self-documenting code. The second case, however, adds very explicit information about what's going on by way of the temporary variable. In these cases, I would say use of a variable is better.
Is there any performance, or other underlying pros or cons to each approach
Performance-wise, assigning an extra variable that you will use only in your if condition will use extra memory, and one useless line of code. So it will use more memory. Will it be noticeable? Probably not.
Stylistically, is any of the approaches considered bad
Using the method in your if statement is perfectly valid, and I think it's a better approach, since you can read the code and see exactly what value is being tested in the if condition. No need to look for the variable and search where it was affected.

does not not_null ever make sense?

I have inherited some code in which the previous coder wrote this:
if (!not_null($page)) {
die('<b>Error!</b><br><b>Unable to determine the page link!<br><br>');
}
Is there any advantage to this, as opposed to just saying:
if (is_null($page))
It seems unnecessarily confusing to me.
not_null must be a local function.
It is not a standard PHP function.
Without knowing what not_null does, it is impossible to say. Since not_null is a user-defined function, it could be doing anything
If, after checking in to things, you find that not_null is doing a simple comparison, you could refactor the code in the name of readability:
if (is_null($page))
die('<p><strong>Error!</strong><br>Unable to determine the page link!</p>')
OR
if ($page === null)
die('<p><strong>Error!</strong>Unable to determine the page link!</p>')
P.S. - don't use <b> -- use <strong> instead. Also, when you need multiple line breaks, use a <p> instead of multiple <br>. Your sample code has an unclosed <b> tag on the error message.
Documentation
http://php.net/manual/en/function.is-null.php
There is no not_null function in PHP I believe.
What should you use?
Use === null or !== null instead of making a call to function explicitly.
It actually seems worse to do so because one can simply write in the if statement:
if($page==null) which evaluates quicker than using this function. You can also try if(!$page) which will evaluate quickly as well.

How does one write a shorthand setter in PHP?

I'm curious is there a way to write a shorthand setter in PHP. My primary quest when writing code is to make it as tight as possible and I think the following is kind of cumbersome:
$value = "Which array do I go in?";
if(true)
$arr_1[] = $value;
else
$arr_2[] = $value;
Is there a better way to write that? I tried to use the shorthand if:
(true)?$arr_1[]:$arr_2[] = "Which array do I go in?";
But that doesn't seem to work. Anyone have any cool tricks for this type of situation?
Thanks!
There is no shorthand for what you are trying to do. Also you should realize that making code "as tight as possible" often comes at the cost of readability.
EDIT: There is some ugly hacks to do what you want, but I would strongly recommend against. E.g.:
$GLOBALS[cond ? 'varname1' : 'varname2'] = $value;
Another hack would be:
$arr = ($cond ? &$arr_1 : &$arr_2);
$arr[] = 'Which array do I go in';
it's two lines but it doesn't require global and would work in a function. However for readability it is probably better to use an if statement. (Note: the & is making a reference to the variable, which is why this works). Another (which might make you understand HOW the ternary operator works) would be:
$cond ? $arr_1[] = $value : $arr_2[] = $value;
You see the ternary operator only evaluates (runs the code path) of the successful evaluation (on the right side of the ? if true, on the right side of : if false). However if you think this is faster than using 'if' you are wrong, your less 'tight' code will actually perform better.
Another option (e.g. if you can't/don't want to use globals).
${$cond?'arr_1':'arr_2'}[] = $value;

checking if a array value is not empty without php warnings

I'm using Zend_Form subclasses to pass array of data to my controllers and sometimes I need some extra logic in the controllers, as such:
$post = $request->getPost();
if (array_key_exists('signatureData', $post) && !empty($post['signatureData'])) {
...
}
To avoid getting php warnings, first, I need to check if the signatureData key exists and only then I can check if the value is not empty.
Anyway I can make this IF statement a little shorter without adding custom php function?
Accepted standard :
if (isset($post['signatureData']) && !empty($post['signatureData']))
Apparently, this is also possible :
if (!empty($post['signatureData']))
-edit-
If you're really lazy, there's a dirty way :
if (#$post['signatureData'])
I'd recommend against it though.
As pointed out in the comments, don't actually use this. It's bad, bad, bad bad, bad. Really though, please don't ever use it. It's only here as a reference.
Using zf, use this
If ($request->getParam('signatureData', false))
Best practice IMO

What is the benefit of using filter_has_var() over isset()

I'm a little confused with the benefit of using filter_has_var($_POST['id']) over isset($_POST['id']).
Can Somebody please tell me if it's simply an alias function?
Not alot ;) According to the manual page for filter_has_var one user finds filter_has_var a little quicker. Also worth noting... filter_has_var isn't working on the live array ($_POST) but on the actual provided input... if you ever add/remove/update what's in that array you won't see those changes with a filter_has_var call (while isset will reflect the current state)
By the way the usage is filter_has_var(INPUT_POST,"id");
Update: Perhaps worth mentioning, filter_has_var was introduced in PHP 5.2.0 (somewhat new) while isset has been around for all of PHP4+5. Most servers keep up to date on this, but isset will always work (no one still runs PHP3 do they?)
First of all, it's not
filter_has_var($_POST['id'])
It's
filter_has_var(INPUT_POST, 'id')
Secondly, it doesn't actually query the $_POST superglobal. It analyzes the request parameter that came in with the request, so it's a better method to use in case $_POST gets dirtied in some way by the PHP script.
I think you mean filter_has_var(INPUT_POST, 'id') over isset($_POST['id']).
There is a small difference in that isset returns false if $_POST['id'] is NULL; you'd have to use key_exists('id', $_POST) to have similar behavior in that regard.
Besides that, the only difference is that filter_has_var doesn't consider modifications to the $_POST array (see this comment).
Function doesn't check live array
<?php
$_GET['a'] = 1;
echo filter_has_var(INPUT_GET, 'a') ? 'Exist' : 'Not exist';
will print Not exist

Categories