I know it may sound a silly question, but I'm trying to make this PHP code as one line:
$value = result_from_a_function();
if ($value > $maximum)
{
$value = $maximum;
}
Is it possible to make it one line in PHP? Something like
$value = result_from_a_function() [obscure operator] $maximum;
The magic function is MIN
$value = min($value, $maximum)
Yes, use a ternary operator:
$value = (result_from_a_function() > $maximum) ? $maximum : $something_else;
Ternary Operators
make code shorter in one line thats why i suggest using ternary operators like
$message = 'Hello '.($user->is_logged_in() ? $user->get('first_name') : 'Guest');
or according to your code sample
$value = (result_from_a_function() > $max) ? $max: $false_Sataments;
Related
Apologies if this is basic, but I'm learning php.
What does this snippet of code actually do? I've seen it in the source code for a plugin but can't quite figure out what's going on
$_POST['newName'] = $_POST['newName'] == "" ? "Dude" : $_POST['newName'];
Thanks.
This is a short version of if...else. This is a Ternary Logic.
$_POST['newName'] = $_POST['newName'] == "" ? "Dude" : $_POST['newName'];
if $_POST['newName'] == "" is true then "Dude" and else $_POST['newName'].
and both the value will be set in $_POST['newName'].
You can write this like this: [Full form]
if($_POST['newName'] == "")
$_POST['newName'] = "Dude";
The ? is also known as the ternary operator. It is called the ternary operator because it takes three operands - a condition, a result for true, and a result for false. If that sounds like an if statement to you, you are right on the money - the ternary operator is a shorthand (albeit very hard to read) way of doing if statements. Here's an example:
<?php
$agestr = ($age < 16) ? 'child' : 'adult';
?>
First there is a condition ($age < 16), then there is a question mark, and then a true result, a colon, and a false result. If $age is less than 16, $agestr will be set to 'child', otherwise it will be set to 'adult'. That one-liner ternary statement can be expressed in a normal if statement like this:
<?php
if ($age < 16) {
$agestr = 'child';
} else {
$agestr = 'adult';
}
?>
So, in essence, using the ternary operator allows you to compact five lines of code into one, at the expense of some readability.
Sometimes while coding, you might feel that writing an if(...){...}else{...} might feel like overkill for small amounts of code:
$result;
if (20>3)
{
$result = "bigger!";
}
else
{
$result = "smaller!";
}
So for this reason, a short hand notation was created where you would be able to express the exact same statement but without the need for such a big structure:
$result = (20>3) ? "bigger!" : "smaller!" ;
Whatever is between = and ? would then be the condition that is normally between the ( and ) of if(...). If that expression then equates to true, the value obtained by $result would be: "bigger!", and if it equated to false, the result would be: "smaller!".
As Frayne said, it is the shortened version of conditional statement. When we write it in full form, it becomes this:
<?php
if($_POST['newName'] == "") {
$_POST['newName'] = "Dude";
} else {
$_POST['newName'] = $_POST['newName'];
}
I have
if ( is_array($this->input->post("tolerance")) )
foreach($this->input->post("tolerance") as $tolerance)
$tolerances .= $tolerance . " " ;
else
$tolerances = 'Not defined';
I want to short code as we all know we are verifying if it is a an array before getting array values
so what would be the correct way to shorten this?
is_array($this->input->post("tolerance")) ? foreach($this->input->post("tolerance") as tolerance) $tolerances .= $tolerance . " " : $tolerances = 'Not defined';
You should/can NOT shorten this at all while keeping the foreach. The ternary operator is not meant to be used like this. It for expressions, not for statements.
Good example:
$foo = xyz() ? 'foo' : 'bar';
Bad example:
xyz() ? foo() : bar();
Worse example (syntax error):
is_array($foo) ? foreach($foo as $bar) ...
The only proper way to shorten your code is using a temporary variable and implode instead of the loop:
$tolerance = $this->input->post('tolerance');
$tolerance = is_array($tolerance) ? implode(' ', $tolerance) : 'Not defined';
In this case the ternary operator is perfectly fine since now you just have a expressions in the then/else parts instead of statements.
Try with implode(), like this:
$tolerances = is_array($this->input->post("tolerance")) ? implode(' ', $this->input->post("tolerance")) : 'Not defined' ;
I can't think of any good way doing this, but be mean and do a:
/* # == ignore expected warning, $r == assign on testing */
$tolerances = ($r = #implode(' ', $this->input->post("tolerance")) ) ? $r : 'Not defined';
I know, most people see this as bad practice.
Another option, to use foreach:
$tolerances = is_array($arr=$this->input->post("tolerance")) ? call_user_func(function($p) { foreach($p as $t) $ts .= $t . " "; return $ts;}, $arr) : 'Not defined';
just following the 'bad practice' philosophy: if its possible, its meant to be.
$tolerances = ( is_array($this->input->post("tolerance")) == false ) ? "Not defined" : implode(" ", implode($this->input->post("tolerance"))) ;
What type do arithmetic operators (+ - / *) have in PHP? I have such situation:
$argX= "1";
$argY = "2";
$operator = "+";
I want to add up two arguments using the operator in the variable. Smth like this:
$result = $argX $operator $argY;
I know that arguments are strings, so I convert them to numbers first.
$argX = $argX+0;
$argY = $argY+0;
But in what should I convert $operator to add the arguments using a value of $operator variable? How is it possible?
No, this is not possible. You cannot use expressions for operators in PHP. Operators are operators, they don't have a type. You'll have to do something like this:
switch ($operator) {
case '+' : $result = $argX + $argY; break;
case '-' : $result = $argX - $argY; break;
...
}
You could eval it, but I wouldn't recommend that.
you can't do that, however you could do
if($operator == '+')
{
//math
}
Something like:
// allowed operators
$allowed = array('+','-','/','*','%');
// check to see that operator is allowed and that the arguments are numeric
// so users can't inject cheeky stuff
if(in_array($operator, $allowed) && is_numeric($argX) && is_numeric($argY)){
eval('<?php $result = '.$argX.' '.$operator.' '.$argY.'; ?>');
}
Wouldn't a function named operator also work?
function operator($X, $Y) {
$Z = $X + $Y;
return $Z
}
$Z = operator($X,$Y);
Is this possible?
$var_1 = 1;
$var_2 = 10;
$comparison = '>';
if($var_1 $comparison $var_2) {
// do something...
}
The syntax right now is not valid but is there a way to do this?
Not natively (except of course with eval). You will need to evaluate the various expressions yourself. Build a wrapper function and use a switch statement. Or for non-expression comparisons a simple map:
$var_1 = 1;
$var_2 = 10;
$comparison = '>';
$map = array(
">" => $var_1 > $var_2,
"<" => $var_1 < $var_2,
"==" => $var_1 == $var_2,
"!=" => $var_1 != $var_2,
);
if($map[$comparison]) {
// do something...
}
It is possible with
if (eval("{$var_1} {$comparison} {$var_2}")) {
But eval is strongly discouraged, so do this only if you can't achieve desired result otherwise
EDIT
As #mario noted, until PHP 5.3 this doesn't work. In 5.3 it does. So for older versions it should be
if (eval("return {$var_1} {$comparison} {$var_2};")) {
You probably should use eval(). As like in other programming languages, PHP’s eval() is also powerful and dangerous — be careful.
If you write something like the following code:
if (eval("$var_1 $comparison $var_2")) {
// ...
}
It won’t work. Because PHP’s eval() doesn’t evaluate an expression, but just execute a statement. So you should do like:
eval("\$condition = $var_1 $comparison $var_2;"); // semicolon required!
if ($condition) {
// ...
}
It would work well except $var_1 or $var_2 is not number. For example, if $var_1 is a string like 'hello', the code eval() executes becomes:
eval("\$condition = hello > 2;");
To avoid breaking this code, you should escape dollar signs of $var_1 and $var_2:
eval("\$condition = \$var_1 $comparison \$var_2;"); // don't escape $comparison's.
I'm not sure if this is possible without the hackish use of an eval statement. You could of course wrap simply test what comparison is being used within another if statement.
if($comparison == '>' && $var_1 > $var_2)
//Do something
elseif($comparison == '<' && $var_1 < $var_2)
//Do something, and so on
The eval method should work too if you build you code into an a string.
if(eval("$var_1 $comparison $var_2")) //Do something
But the first method is probably far more preferable.
You could also create a few functions like isGreaterThan($arg1, $arg2), isLessThan($arg1, $arg2), and then store the name of the function you want in the variable $comparison. Then you would use call_user_func_array() when you want to use it. Like so :
function isGreaterThan($val1, $val2) {
return $val1 > $val2;
}
/////////////
$var_1 = 1;
$var_2 = 10;
$comparison = "isGreaterThan";
if(call_user_func_array($comparison, array($var_1, var_2))) {
//do something
}
Sounds like you've got a few options. Hope this helps.
make the string a conditional, returning a value if true or false
short form if statement
$var_1 = 1;
$var_2 = 10;
$comparison = '>=';
eval("\$b=$var_1 $comparison $var_2?1:0;");
if ($b) {
//do something
}
In PHP, is there a better way to say a variable equals itself, example:
$floor = floor($difference / $key);
if($floor > 1) {
$value .= "s";
} else {
$value .= "";
};
On the fourth line, we're saying $floor equals itself plus an empty string. Is there a better way to do this?
Yes.
You can do nothing.
$floor already equals itself. You can remove the entire else block.
Your updated code still doesn't make sense. You're not assigning, you're concatenating. Is this what you meant to do?
if($floor > 1) {
$value = "s";
} else {
$value = "";
}
You can shorten this using the ternary operator:
$value = ($floor > 1) ? 's' : '';
If $value is already an empty string, you don't need to take any action. Not every if statement has to have a matching else.