Adding string with number in php - php

$a = "3dollars";
$b = 20;
echo $a += $b;
print($a += $b);
Result:
23
43
I have a question from this calculation.$a is a string and $b is number.I am adding both and print using echo its print 23 and print using print return 43.How is it

It casts '3dollars' as a number, getting $a = 3.
When you echo, you add 20, to $a, so it prints 23 and $a = 23.
Then, when you print, you again add 20, so now $a = 43.

The right way to add (which is technically concatenating) strings is
$a = 7;
$b = "3 dollars";
print ($a . $b); // 73 dollars
The + operator in php automatically converts string into numbers, which explains why your code carried out arimethic instead of concatenation

PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.
In PHP 7, type declarations were added. This gives us an option to specify the expected data type when declaring a function, and by adding the strict declaration, it will throw a "Fatal Error" if the data type mismatches.
To specify strict we need to set declare(strict_types=1);. This must be on the very first line of the PHP file. Then it will show fatal error and if you didn't declare this strict then it convert string into integer.

If you need both the values, return them in an array

PHP treats '3dollars' as a integer 3 because string starting with integer and participating in arithmetic operation, so
$a = "3dollars";
$b = 20;
echo $a += $b;
it echo 23; //$a=$a+$b;
now $a = 23 + 20;
print($a += $b); //$a=$a+$b;
it print 43;

Since You have created a variable for the two, it stores the result of each, so when you added $a to 20 it will echo 23 which stores in the system, them when you print $a which is now 23 in addition to $b which is 20. You will get 43.

Related

Is there a clean way to use undefined variables as optional parameters in PHP?

Is there any nice way to use (potentially) undefined Variables (like from external input) as optional Function parameters?
<?php
$a = 1;
function foo($a, $b=2){
//do stuff
echo $a, $b;
}
foo($a, $b); //notice $b is undefined, optional value does not get used.
//output: 1
//this is even worse as other erros are also suppressed
#foo($a, $b); //output: 1
//this also does not work since $b is now explicitly declared as "null" and therefore the default value does not get used
$b ??= null;
foo($a,$b); //output: 1
//very,very ugly hack, but working:
$r = new ReflectionFunction('foo');
$b = $r->getParameters()[1]->getDefaultValue(); //still would have to check if $b is already set
foo($a,$b); //output: 12
the only semi-useful method I can think of so far is to not defining the default value as parameter but inside the actual function and using "null" as intermediary like this:
<?php
function bar ($c, $d=null){
$d ??= 4;
echo $c,$d;
}
$c = 3
$d ??= null;
bar($c,$d); //output: 34
But using this I still have to check the parameter twice: Once if it is set before calling the function and once if it is null inside the function.
Is there any other nice solution?
Ideally you wouldn't pass $b in this scenario. I don't remember ever running into a situation where I didn't know if a variable existed and passed it to a function anyway:
foo($a);
But to do it you would need to determine how to call the function:
isset($b) ? foo($a, $b) : foo($a);
This is kind of hackish, but if you needed a reference anyway it will be created:
function foo($a, &$b){
$b = $b ?? 4;
var_dump($b);
}
$a = 1;
foo($a, $b);
I would do something like this if this was actually a requirement.
Just testing with sum of the supplied values just for showing an example.
<?php
$x = 1;
//Would generate notices but no error about $y and t
//Therefore I'm using # to suppress these
#$sum = foo($x,$y,4,3,t);
echo 'Sum = ' . $sum;
function foo(... $arr) {
return array_sum($arr);
}
Would output...
Sum = 8
...based on the array given (unknown nr of arguments with ... $arr)
array (size=5)
0 => int 1
1 => null
2 => int 4
3 => int 3
4 => string 't' (length=1)
array_sum() only sums up 1,4 and 3 here = 8.
Even if above actually works I would not recommend it, because then whatever data can be sent to your function foo() without you having any control over it. When it comes to user input of any kind you should always validate as much as you can in your code before using the actual data from the user.

PHP- Maintain leading 0 in number [duplicate]

I need to add numbers in php without changing the number format like below
$a = "001";
$b = "5";
$c = $a+$b;
Now the result comes like "6" but I need "006" if $a is "01" then the result should be "06".
Thanks
Technically speaking, the $a and $b in your example are strings - when you use the addition operator on them they converted to integers which can't retain leading zeroes. More details on string-to-number conversion are in the manual
Something like this would do it (assuming positive integer strings with leading zeros)
#figure out how long the result should be
$len=max(strlen($a), strlen($b));
#pad the sum to match that length
$c=str_pad($a+$b, $len, '0', STR_PAD_LEFT);
If you always know how long the string has to be, you could use sprintf, e.g.
$c=sprintf('%03d', $a+$b);
Here, % introduces a placeholder, 03 tells it we want zero padded to fill at least 3 digits, and d tells it we're formatting an integer.
Hope this would help you:
<?php
$a="001";
$b="5";
$l=max(strlen($a),strlen($b));
$c=str_pad($a+$b, $l,"0", STR_PAD_LEFT);
echo $c;
?>
For common case. Your code should looks like this.
$a = someFormat($original_a);
$b = someFormat2($original_b); // $b has different format.
$c = someFormat($a + $b);
Or, you need write formatRecognition function.
$a = getValueA();
$b = getValueB();
$c = someFormat(formatRecognition($a), $a + $b);

Concatenation-assignment in PHP

I am learning PHP and I just read about Assignment Operators and I saw this
$a .= 5 which means $a equals $a concatenated with 5. To test this I coded a simple script
<?php
$a = 12345;
$a .=6;
$b = 12345;
$b .=006;
$c = 12345;
$c .=678;
echo " a=$a and b=$b c=$c" ;
?>
the output was a=123456 and b=123456 c=12345678.My question is why the b isn't equal with 12345006? Is it because treats 6 == 006?
Because 006 is treated as the octal number 6, which is the converted to the string "6", and concatenated to "12345" (which is the number 12345 converted to a string).
Use $b .= "006", and the result will be 12345006.
Because numbers with leading zeroes are treated as octals. if the concatenation would've included the leading zeroes, then 006 would've been interpretted as a string, which makes no sense, because it hasn't got quotes around it.
If you want 006 to be treated as a string, write it as one: '006'. Leave it as is, and it'll be interpreted as an octal:
$b = $a = 123;
$a .= 8;
$b .= 010;//octal
echo $a, ' === ', $b, '!';//echoes 1238 === 1238!
Just as an asside: yes, those are comma's/. echo is a language construct to which you can push multiple values, separated by comma's. The upshot of using comma's is that the values aren't concatenated into a single string before being pushed to the output stream.
This means that it is (marginally faster). The downsides: there aren't any AFAIK.
In case you're interested in the internals of PHP, I've explain this a bit more detailed here...
Just try b as a string:
$b.= '006';
Then you will get output 12345006.

If $a = 5, $b = 'a', what is the value of $$b?

Explain this interview question to me:
Q: If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b?
A: 5, it’s a reference to existing variable.
That's a variable variable. PHP will look up the variable with the name stored in the string $b. So if $b == 'a' then $$b == $a.
It's a lot like pointers in C, except they use variable name strings instead of memory addresses to point to each other. And you can dereference as many times as you want:
$a = 5;
foreach (range('b', 'z') as $L) {
$$L = chr(ord($L) - 1);
}
echo $$$$$$$$$$$$$$$$$$$$$$$$$$z;
Output:
5
-95 is the answer as if u will echo $b u will get output as
"a"
and if u echo $a u will get out but as "5"
hence in this sense when u $(echo $b) which same as $(a) hence u will get it as "5-100" which is "-95"
$$b - 100
= $a - 100 // substituting $b=a
= 5 - 100
= -95
I don't know if the '?' is erroneous in the statement '$$b? - 100' but I don't think that will compile.
However:
$a = 5
$b = 'a';
$c = $$b - 100;
$c will equal -95, because $$b is a variable variable reference and given that $a = 5 it resolves to $a (5) - 100, or -95.
the answer is -95
$a - 100
The following is a good reference on PHP variables
http://php.net/manual/en/language.variables.variable.php

A function to get the smaller number

I have 2 variables each containing a number (integer). I would like to sort them to have the lowest number first and the second largest. For example:
$sortedVar = getSmaller(45, 62); // Will return 45
$sortedVar = getSmaller(87, 23); // Will return 23
Do you see what I want to do? Can you help me please?
Thanks :)
http://php.net/manual/en/function.min.php
min — Find lowest value..
If the first and only parameter is an array, min() returns the lowest value in that array. If at least two parameters are provided, min() returns the smallest of these values.
Note:
Values of different types will be compared using the standard comparison rules. For instance, a non-numeric string will be compared to an integer as though it were 0, but multiple non-numeric string values will be compared alphanumerically. The actual value returned will be of the original type with no conversion applied.
Caution
Be careful when passing arguments with mixed types values because min() can produce unpredictable results...
Use min() which supports any number of arguments as well as arrays.
$smallest = min(1,2); //returns 1
$smallest = min(4,3,2); //returns 2
$smallest = min(array(5,4)) //returns 4
function getSmaller($a, $b) {
return $a < $b ? $a : $b;
}
In plain english, if $a is smaller than $b, then return $a, else return $b.
Or as others pointed out, there's also a function for that, called min().
$sortedVar = $a < $b ? $a : $b;

Categories