Concatenation 2 variable PHP - php

This is not the first time I encountered the problem. I have 2 variables in PHP of type string. When both of them are not empty I want something like this :
echo $var1 . ', ' . $var2;
My problem is that sometimes $var1 or $var2 could be empty so the coma is floating. I try this :
echo $var1 && $var2 ? $var1 . ', ' . $var2 : $var1 || $var2;
But when we are in the right condition, it send 1. I hope the only way is not to test $var1 && $var2 then test $var1 and then test $var2.
Thanks in advance,

echo join(', ', array_filter([$var1, $var2]));
array_filter removes all empty values, and join puts the joiner between the remaining items, if there are more than one.

You can do it by many way e.g by checking empty, using ternary and so on but I've one way to fix this using array_filter() to remove empty values and implode with , . Then it'll not floating when any of the variable is empty string and it can consume multiple variables. Hope this helps :)
<?php
$implode = ', ';
$var1 = 'xyz';
$var2 = '';
$result = [$var1,$var2];
$filtered_result = array_filter($result);
echo implode($implode,$filtered_result);
?>
DEMO: https://3v4l.org/PZ8Rv

try this
if(!(empty($var1) && empty($var2))){
echo $var1 . ', '.$var2;
}else{
$value = !empty($var1)? $var1 : (!empty($var2)? $var2 : "both are empty");
echo $value
}

your right condition use || operator which returns a boolean. if the right statement or left statement is true it will return true (1), or it will return false (0)
then you have to do something like this
echo ($var1 && $var2 ? $var1 . ', ' . $var2 : ($var1 ? $var1 : $var2));
note that $var1 has to be defined (null or empty but it has to be defined)

Related

Stop giving error number_format for PHP

Here is question:
$var = 1000;
$var2 = number_format($var,2);// No error
And;
$var = 'Some String';
$var2 = number_format($var,2);// Gives 'number_format() expects parameter 1 to be double.... error'
My handling solution is;
$var = 'Some String';
$var_escape = 1000;
if(!$var2 = number_format($var,2)){
$var2 = $var_escape;// if $var not a integer; always give 1000 to $var2.
}
This solution working perfectly but; still giving "expect parameter error"; because of this line:
if(!$var2 = number_format($var,2)){
I don't want to use "#" supression. Is there any other solution for this issue? Thanks...
MY INSPIRED BY ANSWERS SOLUTION
if(!is_numeric($var2 = $var)){$var2 = $var_escape;}
Thanks all...
You can check if your input is a number or not using is_numeric function
$var = 'Some String';
$var_escape = 1000;
if(is_numeric($var))
$var2=number_format($var,2);
else
$var2=$var_escape;
You can simply just declare $var2 in advance with the default value, then check to ensure that incoming value of $var is numeric using the built-in is_numeric() function in PHP. If the incoming value of $var is indeed numeric, assign that numeric value to $var2, else $var2 will remain as the default 1000 as it's value.
$var2 = 1000;
if(is_numeric($var)){
$var2 = number_format($var,2);
}
// You can proceed to use $var2 here as it will be 1000 or the value from $var if it was numeric.
Be careful... Demo
Use:
if(is_float($var) || is_integer($var)){
Instead of:
if(is_numeric($var)){
Unless you want your numeric strings to be processed as well.
Using a regex will be the easiest, this verifies that it's either an integer or a float.
code
$vars = array(
'Some String',
123,
123.5,
-11,
"123.55",
"$2!!",
.1,
1,
".1",
"1"
);
foreach($vars as $var) {
if(0 !== preg_match('/^-?\d*\.?\d*$/', $var)) {
echo number_format($var, 2) . PHP_EOL;
} else {
echo $var . " -> " . 1000 . PHP_EOL;
}
}
output
Some String -> 1000
123.00
123.50
-11.55
123.55
$2!! -> 1000
0.10
1.00
0.10
1.00

php reverse concatenation operator like .=

Don't think this exists but just want to make sure.
Is there a reverse for the .= operator in php.
example:
[$x .= $y] === [$x = $x.$y]
looking for:
[$x ? $y] === [$x = $y.$x]
No, there isn't.
The PHP manual documentation only lists two operators:
There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends the argument on the right side to the argument on the left side.
When you want to prepend to a string, just do $str = $add . $str. There is no need for a "special operator" here. If you use it frequently and don't want to retype it every time, you can create a function like this:
function prepend($text, $add) {
return $add . $text;
}
But, as you can probably guess, it's pointess.
Amal Murali's answer gave me an idea.
function p(&$x,$y){
$x = $y.$x;
return $x;
}
Now instead of having to type out;
$var1 = $var2 . $var1;
You can just do:
p($var1, $var2);
If you send the first variable as reference it does clean the code a bit.
Variables:
$var = ' world';
$var2 = 'Hello';
Usage
echo p($var, $var2);
or
p($var, $var2);
echo $var;
is now equal to:
$var = $var2 . $var1;
echo $var;

Concatenate two integers in php

I know it is possible in php to concatenate two strings like
$a .= $b;
which is equal to
$a = $a . $b;
Is it possible to do something with integers? but with math operations? I have two variables:
$var1 = 8;
$var2 = 2;
I need to do $var1 - $var2, but I don't want to create third variable to hold this calculation. I would try $var1 = $var1 + $var2 will this work? Is there another .= similar way of doing it?
OK, because everybody is confused now
// _Appending_ $var2 to $var1 and assign it to $var1
$var1 .= $var2;
// _Add_ $var2 to $var1 and assign the result to $var1
$var1 += $var2;
There is nothing more to remember than, that every binary operator is combineable with the assignment. Within the engine it's always expanded to
$var1 = $var1 . $var2; // You can imagine how the others looks like
In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic, array union and string operators that allow you to use a value in an expression and then set its value to the result of that expression.
I think you need a string formatting.
$var1 = sprintf( "%d%d", $var1, $var2 );
which will make your $var1 as 82.
As in C and C++, PHP supports Compound_assignment_operators:
So, the line:
$var1 = $var1 + $var2;
is equivalent to:
$var1 += $var2;
For full list of those operators, take a look at Compound_assignment_operators
Yes
$var1 = 1
$var2 = -1;
$var1 += $var2; // $var1 = 0
Yes, Compound Assignment operators will work in php as C & Java.
you can try like this
$Var1+=$Var2;
$var1=$var1-$var2;
will work fine, but shorthand operators like
$var1=-$var2
will not work.
I will set -2 to $var1
Notation for shorthand operator is :
$var1-=$var2;

PHP Datatype mismatch on comparison

So I have 2 variables, var1, var2.
$var1 = "53,000,000" //- integer
$var2 = 10 //- string
In the end I want to compare both, so I
$var1 = (int)str_replace(",","",$var1); // => 53000000 - integer
Here's my issue .. if I do:
if($var1 > $var2)
$var2 = $var1
I get $var2 = 0 .... Why ?
.. running on PHP 5.2.14
EDIT Accidentally typed in substr_replace instead of str_replace. Updated.
I had to add a couple semicolons, but here's the code:
$var1 = "53,000,000"; //- integer
$var2 = 10; //- string
//In the end I want to compare both, so I
$var1 = (int)str_replace(",","",$var1); // => 53000000 - integer
//Here's my issue .. if I do:
if($var1 > $var2)
$var2 = $var1;
var_dump($var1, $var2);
And here's my output:
int(53000000) int(53000000)
I used 5.2.6, but it shouldn't matter. Do you have any other code in between what you're showing?
Use str_replace() instead of substr_replace().
You've specified the wrong parameters for substr_replace, so $var1 is evaluated to 0. I guess you wanted to use str_replace.
No need for type casting. just do the str_replace
Here is code
$var1 = "53,000,000" ;
$var2 = 10;
$var1=str_replace(',','',$var1);
if($var1 > $var2)
$var2 = $var1;
echo $var2;

Finding a smaller value and swap values in php

$var1 = 22;
$var2 = 10;
echo $var1 = ($var1 < $var2) ? $var1 : $var2; //smaller var
echo '';
echo $var2 = ($var1 > $var2) ? $var1 : $var2; //greater var
I expect it to print 10 and 22 but it prints 10 and 10. any ideas what I am doing wrong?
Thanks
UPDATE
Thanks all.
$min = min($var1, $var2);
$max = max($var1, $var2);
$var1 = $min;
$var2 = $max;
#unicornaddict already solved your problem, but to make it simpler you can use the min and max functions PHP provides.
echo min($var1, $var2), '<br/>', max($var1, $var2);
You are re-assigning the variables in the echo.
// $var1 is being assigned minimum of 10,22 which is 10.
// after this $var1 and $var2 will both be 10.
echo $var1 = ($var1 < $var2) ? $var1 : $var2;
What you want it:
echo ($var1 < $var2) ? $var1 : $var2; // prints min.
echo '<br />';
echo ($var1 > $var2) ? $var1 : $var2; // prints max.
EDIT:
If you always want the smaller of the two values in $var1 you can do:
if($var1 > $var2) { // if $var1 is larger...swap.
list($var1,$var2) = array($var2,$var1);
}
You overwrite $var1 in your first comparison. So the second comparison compares 10 > 10.
$var1 = 22;
$var2 = 10;
echo $var1 = (10 < 22) ? 22 : 10; //smaller var -> $var1 now has the value 10
echo '<br />';
echo $var2 = (10 > 10) ? 22 : 10; //greater var -> 10 is not greater than 10, so $var2 gets a value of 10.
you assign 10 to $var1 with the first echo, so at the second they are both 10.
echo $var1 = ($var1 < $var2) ? $var1 : $var2; //smaller var
This assigns 10 to $var1. Now both variables contain 10. So what do you expect of the second line?
You need a temporary variable. Just use min,
echo min($var1, $var2);
Your question also mentions swapping the values, which the other answers don't seem to make any note of. Given your example code it looks like you want $var1 to contain the smaller of the two values and $var2 the bigger.
$var1 = 22;
$var2 = 10;
if ($var1 > $var2) {
list($var1, $var2) = array($var2, $var1);
}
// $var1 will now be smaller than (or equal to!) $var2

Categories