PHP cast to integer with only 1 or 2 chars - php

How can I cast to integer in PHP using only 1 or two chars?
If I have the operation $a = (int) $b; it will result using those two (or one) chars:
$a = <*insert the needed 1 or 2 chars*> $b;
I need only to cast to integer. Thank you.

Prefix a + (the unary plus):
$a=+$b
A pretty common trick for code-golfing that also works in PowerShell and other languages.
$ php -r "var_dump('4');"
string(1) "4"
$ php -r "var_dump(+'4');"
int(4)

$a = sprintf("%02d", $b);
If you need to pad it with something other than zero, replace the zero with the character you need.

You can make a function, I guess. Of other type of shorter cast I'm unaware.
function z($i)
{
return (int)$i;
}
$a = z($b);

Related

PHP ignore dollar sign

PHP
<?php
$a = $offer->service_original_price_display;
$b = $offer->service_discounted_price_display;
$c = $a - $b;
?>
However I am getting this error: A non-numeric value encountered since service_original_price_display is '$500' and service_discounted_price_display is '$300'. I assume it is because both contains the dollar sign hence PHP is not able to perform the equation. Is there any solution to this? Thanks!
$a = str_replace("$", "", $offer->service_original_price_display);
$b = str_replace("$", "",$offer->service_discounted_price_display);
$ is string
use trim($a, '$'); to remove both side $ sign
You can use substr, if you know the first place is always occupied by a $ from an error standpoint, removing the $ ( with str_replace ) is probably better. But, as those answers where already posted. I get the scraps ( lol ).
$a = '$500';
$b = '$300';
$c = substr($a,1) - substr($b,1);
echo $c;

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.

What does (int) $_GET['page'] mean in PHP?

I tried looking up (int) but could only find documentation for the function int() in the PHP manual.
Could someone explain to me what the above code does, and exactly how it works?
You can find it in the manual in the section type juggling: type casting. (int) casts a value to int and is a language construct, which is the reason that it looks "funny".
It convert (tries at least) whatever the value of the variable is to a integer. If there are any letter etc, in front it will convert to a 0.
<?php
$var = '1a';
echo $var; // 1a
echo (int) $var; //1
$var2 = 'a2';
echo $var2; //a2
echo (int) $var2; // 0
?>
(int) converts a value to an integer.
<?php
$test = "1";
echo gettype((int)$test);
?>
$ php test.php
integer
Simple example will make you understand:
var_dump((int)8);
var_dump((int)"8");
var_dump((int)"6a6");
var_dump((int)"a6");
var_dump((int)8.9);
var_dump((int)"8.9");
var_dump((int)"6.4a6");
Result:
int(8)
int(8)
int(6)
int(0)
int(8)
int(8)
int(6)
In PHP, (int) will cast the value following it to an int.
Example:
php > var_dump((int) "5");
int(5)
I believe the syntax was borrowed from C.
What you are looking at there is known as type casting - for more information, see the manual page on type juggling.
The above piece of code casts (or converts) $_GET['page'] to an integer.
this kind of syntax (int) is called type casting. Basically it takes the variable following it and tries to force it into being an int
(int) is same as int()
see
http://php.net/manual/en/language.types.integer.php
it casts the variable following it to integer. more info from documentation:
http://php.net/manual/en/language.types.type-juggling.php
Type casting in PHP works much as it does in C: the name of the
desired type is written in parentheses before the variable which is to
be cast.
The casts allowed are:
(int), (integer) - cast to integer
(bool), (boolean) - cast to boolean
(float), (double), (real) - cast to float
(string) - cast to string
(array) - cast to array (object) - cast to object
(unset) - cast to NULL

Strange behaviour of ++ operator in PHP 5.3

Watch following code:
$a = 'Test';
echo ++$a;
This will output:
Tesu
Question is, why ?
I know "u" is after "t", but why it doesn't print "1" ???
PHP Documentation:
Also, the variable being incremented
or decremented will be converted to
the appropriate numeric data
type—thus, the following code will
return 1, because the string Test is
first converted to the integer number
0, and then incremented.
PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in Perl 'Z'+1 turns into 'AA', while in C 'Z'+1 turns into '[' ( ord('Z') == 90, ord('[') == 91 ). Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.
Source: http://php.net/operators.increment
In PHP you can increment strings (but you cannot "increase" strings using the addition operator, since the addition operator will cause a string to be cast to an int, you can only use the increment operator to "increase" strings!... see the last example):
So "a" + 1 is "b" after "z" comes "aa" and so on.
So after "Test" comes "Tesu"
You have to watch out for the above when making use of PHP's automatic type coercion.
Automatic type coercion:
<?php
$a="+10.5";
echo ++$a;
// Output: 11.5
// Automatic type coercion worked "intuitively"
?>
No automatic type coercion! (incrementing a string):
<?php
$a="$10.5";
echo ++$a;
// Output: $10.6
// $a was dealt with as a string!
?>
You have to do some extra work if you want to deal with the ASCII ordinals of letters.
If you want to convert letters to their ASCII ordinals use ord(), but this will only work on one letter at a time.
<?php
$a="Test";
foreach(str_split($a) as $value)
{
$a += ord($value); // string + number = number
// strings can only handle the increment operator
// not the addition operator (the addition operator
// will cast the string to an int).
}
echo ++$a;
?>
live example
The above makes use of the fact that strings can only be incremented in PHP. They cannot be increased using the addition operator. Using an addition operator on a string will cause it to be cast to an int, so:
Strings cannot be "increased" using the addition operator:
<?php
$a = 'Test';
$a = $a + 1;
echo $a;
// Output: 1
// Strings cannot be "added to", they can only be incremented using ++
// The above performs $a = ( (int) $a ) + 1;
?>
The above will try to cast "Test" to an (int) before adding 1. Casting "Test" to an (int) results in 0.
Note: You cannot decrement strings:
Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.
The previous means that echo --$a; will actually print Test without changing the string at all.
The increment operator in PHP works against strings' ordinal values internally. The strings aren't cast to integers before incrementing.

Categories