What will pass through this statement?
$a=($_POST['a']*1337)+1.7;
$a=!preg_match('/[^0-9]/',''.$a)?(int)round($a)-33:1337;
My goal is to make $a == 'float';
$a=!preg_match('/[^0-9]/',''.$a)?(int)round($a)-33:1337;
$a is set to the ternary result of the negation of the return of preg_match(), which tests the regex [^0-9] on $a concatenated with an empty string. The responses are round()ed and cast to integer $a - 33 or 1337.
I'd say this code could be written much nicer as...
$a = preg_match('/\D/', (string) $a) ? 1337 : (int) round($a) - 33;
if your goal is to make $a float then just try casting:
$a = (float) $_POST['a'];
Better Way (KISS Theory)
$a=$_POST['a']*1337+1.7;
if(preg_match('/\D/', (string) $a))
$a = 1337
else
$a = (int) round($a) - 33;
Note: instead of (int) round($a) you should use either floor or ceil
Related
I have an unknwon string that could resemble a float. In that case I want to convert it to float (for calculations), otherwise leave it as a string.
How do I detect if a string represents a float number?
$a = "1.23"; // convert $a to 1.23
$b = "1.2 to 1.3"; // leave $b as is
Automatic string conversion would convert the latter to 1.2, but that's not what I want.
You can use is_numeric() function to check variable which might contain a number.
For example:
$a = "1.23";
if (is_numeric($a)) {
$a = (float)$a;
}
$b = "1.2 to 1.3";
if (is_numeric($b)) {
$b = (float)$b;
}
var_dump([
'a' => $a,
'b' => $b
]);
Output
array (size=2) 'a' => float 1.23 'b' => string '1.2 to 1.3'
(length=10)
You can use the following to check if a string is a float:
$a = "1.23";
$isFloat = ($a == (string)(float)$a);
function StrToFloat($var){
if(is_numeric($var)){
return (float)$var;
} else return $var;
}
$a = "1.23"; // convert $a to 1.23
$b = "1.2 to 1.3"; // leave $b as is
$a = StrToFloat($a); // $a = 1.23
$b = StrToFloat($b); // $b = "1.2 to 1.3"
Because it hasn't been mentioned
if(preg_match('/^\d+\.\d+$/', $string)){
$float = (float)$string;
}
I think is_numeric is a better choice, but this works too.
What I have above only matches floats, so they have to have the decimal. To make that optional use /^\d+(\.\d+)?$/ instead.
^ start of string
\d+ one or more digits
\. the dot, literally
\d+ one or more digits
$ end of string
For the second one /^\d+(\.\d+)?$/ it's the same as the above except with this addition:
(...)? optional capture group, match this pastern 0 or 1 times.
Which it should now be obvious is what makes the decimal optional.
Cheers!
maybe you would like to use the non-locale-aware floatval function:
float floatval ( mixed $var ) - Gets the float value of a string.
Example from the documentation:
$string = '122.34343The';
$float = floatval($string);
echo $float; // 122.34343
Simple maths:
$a=$b/$c; echo $a;
if $b equals to 123.00 and $c equals to 1 then $a becomes 123.
If $b is 123.50, $c is 1, $a is 123.50. But in the former case , I want $a to be 123.00.
It is possible to test whether $a has any non-zero fraction part or not, and then add the trailing zeros as necessary.
But I am looking for php functions to do the same thing. Possible?
EDIT :
What if I do not want the commas from number_format there ?
Use sprintf("%0.2f",$a);. docs
Use the number_format function. If you don't want comma separators, set all four parameters of the function like so (the thousands separator is the fourth parameter):
$number = number_format(1234, 2, '.', '');
Yup, using https://www.php.net/manual/en/function.number-format.php function like this:
$a = 123;
$answer = number_format($a,"2");
echo $answer;
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);
in this simple PHP code
why php parser return true?
$text="51.406ABC917";
$floatval = floatval($text);//51.406
if($floatval==$text){
$result_compare = true;//php parser return true
}else{
$result_compare = false;
}
It's about Type Juggling and PHP type comparison tables, and Comparison Operators. Just check it.
Type of Operand 1:string, resource or number
Type of Operand 2: string, resource or number
Translate strings and resources to numbers, usual math.
You could avoid convertion to float by adding typecasting to string.
if((string)$floatval==$text){
$result_compare = true;
}else{
$result_compare = false; //php parser return false
}
== will compare the data ,use === to compare data and datatype
$floatval==$text
in the above comparison you are comparing a float value with a string
try with === instead of ==
Look here . You should never compare floats for equality.
You need use the epsilon technique.
For example:
if (abs($forstFloat - $secondFloat) < epsilon) {
echo 'they are equal!!'
}
where epsilon is constant representing a very small number.
$a == $b Equal TRUE if $a is equal to $b after type juggling.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type.
Take this as example
<?php
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("10" == "1e1"); // 10 == 10 -> true
var_dump(100 == "1e2"); // 100 == 100 -> true
switch ("a") {
case 0:
echo "0";
break;
case "a": // never reached because "a" is already matched with 0
echo "a";
break;
}
?>
Reference
Try this,
$text="51.406ABC917";
$floatval = floatval($text);//51.406
if($floatval===$text){
$result_compare = 'true';//php parser return true
}else{
$result_compare = 'failed';
}
LOGIC:
$a == $b Equal TRUE if $a is equal to $b after type juggling.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type.
Ref: http://www.php.net/manual/en/language.operators.comparison.php
Before comparison $text is converted to a float , with same result as floatval(),
then you compare $floatval==$text, so result is pretty predictable - TRUE
It's normal, when you compare variables from 2 different types, first them to be converted to closest same type.
I would suggest, when comparing float, use similar construct
if ( abs($floatval - floatval($text)) < 0.001 ) {..}
compare difference between 2 floats, instead them. Cause if u have 2 numbers, 45 and 45.00001 , php will think they differ.
What do you wanna accomplish ? Why you think this result is wrong ?
try this:
<?php
$text="51.406ABC917";
$floatval = floatval($text);//51.406
if(strval($floatval)==$text){
$result_compare = true;//php parser return true
}else{
$result_compare = false;
}
?>
If first part of string is numbers, it will be converted to numbers otherwise it will be zero (0). Yes, to compare value and type of variable, use === instead of ==.
But in your case, you already convert string to float by floatval($text); then === same as ==.
The problem is how php convert string to number by floatval($text);
This is how php convert string to numbers:
<?php
$foo = 1 + "10.5"; // $foo is float (11.5)
$foo = 1 + "-1.3e3"; // $foo is float (-1299)
$foo = 1 + "bob-1.3e3"; // $foo is integer (1)
$foo = 1 + "bob3"; // $foo is integer (1)
$foo = 1 + "10 Small Pigs"; // $foo is integer (11)
$foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2)
$foo = "10.0 pigs " + 1; // $foo is float (11)
$foo = "10.0 pigs " + 1.0; // $foo is float (11)
?>
Full document here: http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion
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