Quick question to do with php functions, it may sound silly to some of you but I dont want to get in to bad habits. Is there anything wrong with doing the following?
function do_something($val)
{
$a = 1;
if ($val==$a)
{
return true;
}
return false;
}
Instead of;
function do_something($val)
{
$a = 1;
if ($val==$a)
{
return true;
}
else
{
return false;
}
}
Sorry guys I think my example isn't great. Basically the function could insert data into a database or send an email etc. With these functions I may only need to now whether it was successful or not by returning true or false. I wanted to know whether its suitable that I can use the shorter method instead of the if-else block.
I hope that makes it clearer.
Not really. Both works the same. However, it would be much cleaner to write it like this:
function do_something($val)
{
$a = 1;
return ($val==$a) ? true : false;
}
That's totally cool, because when returning a value, the function is left and it doesn't matter what follows.
But you could shorten this with
function do_something($val)
{
$a = 1;
return $val == $a; // this condition will be evaluated to true/false
}
The shortest way to do it:
function do_something($val)
{
return ($val==1) ;
}
No, that is perfectly fine, and in fact advised in multiple cases. :)
Related
I want to make condition with shorthand if and use return in condition how can I do something like this
Here is my controller
public function index()
{
$all = User::all()
$all = $this->calculatePercent($all);
return view('dashboard.index');
}
I want to make condition
If (!empty($user)){
$user = $user;
} else {
return 0
}
How can I do something like this :
public function calculatePercent($user)
{
$query = !empty($user) ? $user : return 0;
}
Update I want to do some thing like this in my function
public function calculatePercent($user)
{
$user = !empty($user) ? $user : return 0;
foreach ($user as $item) {
$percentSell[] = ($item->total * 100)/$item->target;
}
return $percentSell;
}
Hi unfortunately you currently cannot return from one of the condition of a trinary expression (short hand if).
Doing:
$foo = true ? return true : false;
Give you
syntax error, unexpected 'return'
That said for single line if's you can omit the {} curly brackets
if(true) return true; else $foo = false;
Which really is not that much longer. I'm not sure exactly why this is the case (cant do it in trinary). It could be because it has sort of an implied return. It could be because returning ends whatever scope you are in and the trinary cannot be completed because of that. Or it could be because it can do assignment such as this (as seen above):
$foo = true ? return true : false;
$foo = return true; //this gives the same syntax error
Well for whatever reason, it's just not possible in the current version of PHP. Perhaps sometime in the future they may do it, but it seems like a low priority sort of thing, so I wouldn't hold my breath ... lol
Just for completeness you can change this:
$query = !empty($user) ? $user : return 0;
Into
if(!empty($user))$query=$user;else return 0;
Also notice you can remove spaces in certain places. Shorthand stuff like this is fine, but there is something to be said about readability. For this it's probably fine, but readability is very important in code and it's much more important then being concise and short, IMO.
When I write code my priorities are
that it achieves the desired result
that it is readable
that it is concise (not bloated)
that it preforms well
If it doesn't do what it's supposed to it's worthless, if you can't read it it's hard to maintain and make sure it does what it's supposed to. If it has a lot of unnecessary bloat it's hard to read and probably performs poorly. Once all those are met, then if I need to I will try to improve the performance of it.
Anyway happy coding!
public function calculatePercent($user)
{
if (empty($user)) return 0; // if $user is empty code ends here with return 0.
foreach ($user as $item) {
$percentSell[] = ($item->total * 100)/$item->target;
}
return $percentSell;
}
im just learning php
Im trying to add a log with comments to my functions output.
Right now it looks like this:
//the function
function add1($x){
if($GLOBALS['logging'] === 'on'){ $log[] = 'Adding 1 to '.$x;};
$a = $x + 1;
if($GLOBALS['logging'] === 'on'){
$return[] = $a;
$return[] = $log;
return $return;
}else{ return $a; };
};
//calling the function
if($GLOBALS['logging'] === 'on'){
$return = add1($x);
$number = $return[0];
$log = $return[1];
}else{ $number = add1($x); };
Im kinda annoyed by the fact i need to retype this if statement.
So i made a seperate function for returning the function
which looks like this:
//function
function log_return($data = 'x', $log = 'x'){
if($GLOBALS['logging'] === 'on'){
if($data !== 'x') $return[] = $data;
if($log !== 'x') $return[] = $log;
return $return;
} return $data;
};//function end
And returning it with:
return $return = isset($log) ? log_return($data, $log) : log_return($data);
Now my quastion is: Is there a way to call a function with function..
like:
call_function(add1($x));
so i can return it either with log or without..
Given the answer https://stackoverflow.com/a/2700760/5387193 - this should work:
function add1($a)
{
// add1 code goes here
}
function call_function($name, $param)
{
$name($param);
}
call_function('add1', $x);
On a side note, your variable and function names aren't very intuitive. Perhaps you should study how to write good quality readable code. I recommend reading chapter 9 of Refactoring by Martin Fowler, it's quite good. You can find a PDF version on the web.
Another note, your return statement return $return = isset($log) ? log_return($data, $log) : log_return($data); has a unnecessary assignment to $return. The code should simply read
return isset($log) ? log_return($data, $log) : log_return($data);
Yes, it is possible. To simplify:
function first($x) {
return $x+1;
}
function second($y) {
return $y+1;
}
echo second(first(1)); // Returns 3, ie. 1+1+1
As gview said in his comment, don't use global variables. Argument lists exist for several reasons, included but not limited to making code easier to read, edit, and debug. The same goes for function and variable names.
Moreover, your code is very messy. It can be consolidated:
function addTo($currentValue, $valueToAdd, $logging = 0)
{
if ($logging) {
logWrite('addTo', "Adding $valueToAdd to $currentValue");
return $currentValue + $valueToAdd;
} else {
return $currentValue;
}
}
function logWrite($operation, $message)
{
$log = getLog(); // maybe it's a file, or DB record or something
// perform the write, depending on your implementation
}
$number = addTo($someStaringValue, $someOtherValue, 1);
All of this said, logging should not control program flow. In other words, whether something is logged by the system or not should have no bearing on what your code is trying to do. I really think you need to take a broader view of what you're trying to do and break it up into components.
At best, your code should tell a logger to log info, and the logger itself should determine if logging is actually turned on. If it is, the info is logged. If not, then the code that calls on the logger still works and goes about its business.
What should one use?
This, without else:
function($condition) {
if($condition) {
return true;
}
return false;
}
Or this, with an else:
function($condition) {
if($condition) {
return true;
} else {
return false;
}
}
What are potential drawbacks?
Note: I understand that right solution for this very example would be
function($condition) {
return (boolean)$condition;
}
I like this approach:
function($condition) {
$retValue = false;
if($condition) {
$retValue = true;
}
return $retValue;
}
This way you know where this function will return, (always at the end) which is good for later analyzing. You set a default value and only change it if the condition is right.
With else there is a better readability. However, both the functions are doing the same as the function is terminated by the return function. I find it also safer to use the else if in some cases you can forget using the return function which then go further to return the false.
I would use the else too, for these reasons:
Your code is better readable
In complex code, like when you use if/else within other if/else's, debugging will be much easier.
In some cases it is possible to increase readability by setting "else" aside. Two examples below are eqiuvalent. Second produces less code, though it will suit only when we return values without complex calculations in that block, but again, we can utilize functions to make it usable.
function($a, $b) {
if($a) {
if($a > $b) {
return true;
} else {
return false;
}
} else {
return false;
}
}
function($a, $b) {
if($a) {
if($a > $b) {
return true;
}
}
return false;
}
Note: if not speaking about general cases with more complex conditions assumption, this should fold to:
function($a, $b) {
return ($a and $a > $b);
}
In the first one both true and false will be returned, as when the if statement finishes, it will go and do the very next thing, return false. In the second one, one true OR false will be returned, depending on the condition. Draw backs for the first one would be that you get both true and false returned, which could confuse a function that's only asking for one parameter, and receiving two instead. This is assuming that you include this inside a larger function. I'm not sure why you would want to use the first one though. Hopefully this helps!
I think the below is a very standard procedure that everyone had written it a hundred times in any of their applications:
$orderByColumnName = '';
if (isset($this->urlParams()['orderby']) {
$orderByColumnName = $this->urlParams()['orderby'];
}
$this->someSortingFunction($orderByColumnName);
I've been doing such way numerous time, I'm feeling sick of it.
There's some kind of like global understanding that suppressing error is evil.
Despite the code can be written so clean by just:
$this->someSortingFunction(#$this->urlParams()['orderby']);
And a ternary shorthand true ?: false; is something close but not useful in this situation because there's no presumed isset check on the condition. Thus we still have to write:
$orderByColumnName = !empty($this->urlParams()['orderby'])?$this->urlParams()['orderby']:'';
So how exactly you guys handle this situation? if all the way? Is there any other smarter way that you could share?
Why not change how the urlParams() method operates? PHP doesn't have true method overloading, but you can fake it inside the method.
public function urlParam($param = null) {
//lets assume $internal_array is
//your object's internal array sent through urlParam()
if(is_null($param)) {
return $internal_array;
} else {
return isset($internal_array[$param]) ? $internal_array[$param] : '';
}
}
Doing this would let you you keep your existing code compatible with $this->urlParams()['some_param']usage while enabling you to refactor everything to $this->urlParams('some_param').
Here is a separate static function which returns NULL if value is not present in an array.
public static function value($key, $list, $default = NULL) {
if (is_array($list)) {
return array_key_exists($key, $list) ? $list[$key] : $default;
}
return $default;
}
Can call this everytime we need to use empty(), isset(), array_key_exists()
$this->someSortingFunction(value('orderby', $this->urlParams()));
This is more or less a readability, maintainability and/or best practice type question.
I wanted to get the SO opinion on something. Is it bad practice to return from multiple points in a function? For example.
<?php
// $a is some object
$somereturnvariable = somefunction($a);
if ($somereturnvariable !== FALSE) {
// do something here like write to a file or something
}
function somefunction($a) {
if (isset($a->value)) {
if ($a->value > 2) {
return $a->value;
} else {
return FALSE;
} else {
// returning false because $a->value isn't set
return FALSE;
}
}
?>
or should it be something like:
<?php
// $a is some object
$somereturnvariable = somefunction($a);
if ($somereturnvariable !== false) {
// do something here like write to a file or something
}
function somefunction($a) {
if (isset($a->value)) {
if ($a->value > 2) {
return $a->value;
}
}
return FALSE
}
?>
As a matter of practice, I always try to return from ONE point in any function, which is usually the final point. I store it in a variable say $retVal and return it in the end of the function.It makes the code look more sane to me.
Having said that, there are circumstances where say, in your function as the first line you check if a var is null and if yes you are returning. In this case, there is no point in holdin on to that variable, then adding additional checks to skip all the function code to return that in the end.
So...in conclusion, both ways works. It always depends on what the situation is and what you are more comfortable with.