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.
Related
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;
I am a beginner in PHP and I am trying to separate the input based on the argument. Following is my code but it seems that my $arg variables is never set. Can someone point out my error?
$sender = $_GET['sender'];
$receiver = $_GET['receiver'];
$message = $_GET['message'];
$temp = explode( '.', $message);
$tempcnt = count($temp);
echo $temp[$tempcnt - 1];
if($tempcnt > 2)
{
if($temp[$tempcnt-1] === 'mp4')
{$arg = 3;}
elseif($temp[$tempcnt-1]==='jpg')
{$arg = 2;}
else
{$arg = 1;}
}
echo "Value of arg is" . $arg;
I have even tried with == and === and strcmp in if but still same issue.
Try This:
<?php
$temp strrchr("foo.jpg",".");
if($temp==".mp4")
$arg = 3;
elseif($temp==".jpg")
$arg = 2;
else $arg = 1;
?>
See also the other answers, but one possibility that hasn't been mentioned is that == and === and strcmp all compare case sensitively. So they won't find extensions like .MP4.
The solution in that case would be to use strcasecmp.
However, the first thing to do with problems like this is to output some more diagnostics, so that you can see for yourself what goes wrong. In this example, echo $tempcnt; after its assignment, or else echo "did nothing" after the outer if {..} block.
That way you'll be able to follow what the program flow is.
Issue was caused since i didn't realize i had compared for args > 2. Made it >=2 and viola it done!!
Thanks to #barmar for pointing that out!
I am trying to insert the following if statement into a class but getting the unexpected T_IF error;
class="color_icon_filter '. if ($link_data['id']==$link_data['text']) {$active} .' "
is this not possible or am I doing it wrong?
You shoud open PHP tags to be interpreted server side.
class="color_icon_filter <?php if ($link_data['id']==$link_data['text']) {echo $active} ?>"
EDIT
Or if you're already in PHP tags
echo 'class="color_icon_filter '.($link_data['id']==$link_data['text'] ? $active : '').'"';
It is not possible to concatenate an if statement onto a string.
You can do this instead:
$string = "123";
if ($bar) {
$string .= "456";
}
$string .= "789";
or this:
if ($bar) {
$baz = "456";
} else {
$baz = "";
}
$string = "123" . $baz . "789";
You could also use a ternary operator, but your if condition is (relatively) long, so it risks making your code look even more like line noise.
You're trying to concat in an if statement.
I'm assuming there's an echo in front of that line. You can either convert that to sprintf (http://php.net/sprintf) or put the if before the echo line, set the value of $active, and then concat in just the variable.
Personally, I think sprintf/printf is your better solution.
You cannot use an if statement in the middle of an assignment operation, but there are ways to achieve your desired result:
$active = '';
if ( $link_data['id']==$link_data['text'] ) {
$active = 'active';
}
$class = "color_icon_filter $active";
or a shorter way via the ternary operator:
$active = ( $link_data['id']==$link_data['text'] ) ? 'active' : '';
$class = "color_icon_filter $active";
I am trying to get this:
if($a[2] > $b[2] && $c[2] < 3) echo "bingo";
But because the condition is retrieved from database, I need to get the whole condition into a variable and then somehow find a way to change the variable back into a condition. I thought it will be something along this line:
$condition = "$a[2] > $b[2] && $c[2] < 3";
$evaledCondition = eval("$condition;");
if($evaledCondition) echo "bingo";
Apparently it didn't work. Am I missing something?
eval() returns NULL unless return is
called in the evaluated code
$evaledCondition = eval("return $condition;");
I have an IF statement that consists of two separate function calls
passing values to two variables. Obviously if neither value is 'FALSE'
then the code block is executed:
<?php
class MyValidater {
static function validateString($string) {
if (preg_match("/[A-Za-z]+/", $string)) {
return $string;
} else {
return false;
}
}
}
$firstName = "Daniel";
$surname = "Simmons";
// Dodgy IF statement
if ($first = MyValidater::validateString($firstName) && $second = MyValidater::validateString($surname)) {
print("Success: $first $second");
} else {
print("Fail: $first $second");
}
?>
As you can see both the $first and $second variables should contain
the values held in $firstName and $surname after successfully being
validated by the Static method validateString.
However, the values of the two variables end up: $first = '1' and
$second = "Simmons".
The '1' should be "Daniel" but for some reason $first is being passed
the value '1' or TRUE. If you swap the two assignment statements over
so that $second is evaluated first, you end up with the opposite
outcome as before. $second = '1' and $first = "Daniel"
Can anyone explain why the String value "Daniel" being returned from
the class method is being changed into the int '1' for the first part
of the conditional statement only? I have had a quick look though the
PHP documentation but cannot find an explanation.
For the moment the workaround is to change the return value from the
static method to be true/false and then make $first = $firstName,
etc... upon success. But this involves more code and I would rather
find out why this way does not work.
You need to bracket your expressions:
if (($first = MyValidater::validateString($firstName)) && ($second = MyValidater::validateString($surname)))
What's actually happening is this:
if ($first = (MyValidater::validateString($firstName) && $second = MyValidater::validateString($surname)))
It would be much clearer to just do this (note this code isn't identical to what you have):
$first = MyValidater::validateString($firstName);
$second = MyValidater::validateString($surname);
if ($first && $second)
&& is higher then = in the operator precedence. add brackets and it will work.
http://www.php.net/manual/en/language.operators.precedence.php
you can read about operator precedence here.
Also, setting values inside of an if condition is usually bad practice. If you add the brackets, you will most probably see why (let $first set to false and $second set to a string) => the first will be evaluated, but since it is false then, it won't process further since it will go to the else anyways. => second will not be set correct if first = false.
Try using parenthesis
($first = MyValidater::validateString($firstName)) && ($second = MyValidater::validateString($surname)))
First is getting the result of the first function call AND the second function having a value.
= is for attributions
== is for comparisons, the data type doesn't matter
=== is for comparisons, the data type matters
What is happening is that PHP is assigning $first with “MyValidater::validateString($firstName)) && $second = MyValidater::validateString($surname)”
You need brackets around first compare and second, like this.
if ( ($first = MyValidater::validateString($firstName)) && ($second = MyValidater::validateString($surname))) {