I'm trying to check if a username string is all numbers (but the field is not a numeric field). If so, I need the string to be 5 characters in length by adding leading 0's.
I have this code:
<?php
$getuname = $_GET['un'];
if (mb_strlen($getuname) <= 1){
$getuname = "0".$getuname;
}
if (mb_strlen($getuname) <= 2){
$getuname = "0".$getuname;
}
if (mb_strlen($getuname) <= 3){
$getuname = "0".$getuname;
}
if (mb_strlen($getuname) <= 4){
$getuname = "0".$getuname;
}
echo $getuname;
?>
The above code works for making sure the string is 5 characters by adding zeros, but it's not very pretty and I'm sure there is a much nicer way to do it. Anyone?
Also, this whole piece needs to be wrapped in an IF statement that is checking to see if it contains nothing but numbers in the first place. I tried using !is_numeric, but this doesn't seem to work. I'm assuming because it's not a numeric type field.
You can use is_numeric to check for a numeric field, it doesn't matter whether the variable is a string or not. See example here.
Then you can simply pad using str_pad()
if(!is_numeric($test))
echo $test . ' is not a number!';
else
echo str_pad($test, 5, 0, STR_PAD_LEFT);
Edit: as flixer pointed out, is_numeric() won't actually do what you specifically asked (to check that a string contains only digits, i.e. no periods, commas, dashes etc which would be considered to "be a number"). In this case, use ctype_digit() instead:
$test_number = '123.4';
$test_number2 = '12345';
echo ctype_digit($test_number) ? $test_number . ' is only digits' : $test_number . ' is not only digits';
echo ctype_digit($test_number2) ? $test_number2 . ' is only digits' : $test_number2 . ' is not only digits';
// output:
// 123.4 is not only digits
// 12345 is only digits
The key here is to avoid regex when you have better tools to do the job.
To add a little to this, ctype_digit() might return false when you pass in an integer variable: (example from PHP manual)
ctype_digit( '42' ); // true
ctype_digit( 42 ); // false - ASCII 42 is the * symbol
This can be OK, depending on the situation you're using this in. In your case you're validating a $_GET variable, which is always going to be a string so it won't affect you.
Docs:
str_pad(): http://php.net/str_pad
ctype_digit(): http://www.php.net/manual/en/function.ctype-digit.php
OP Here, this is it all together. Works like a charm...
if (ctype_digit($getuname) == true) {
$getuname = str_pad($getuname, 5, 0, STR_PAD_LEFT);
}
Use the str_pad() function. Like this:
$getuname = str_pad($_GET['un'], 5, '0', STR_PAD_LEFT);
Try this:
<?php
$getuname = $_GET['un'];
if(ctype_digit($getuname))
$getuname = str_repeat("0", 5-strlen($getuname)) . $getuname;
?>
Hope it works for u.
This should be a clean solution:
$getuname = $_GET['un'];
if(preg_match('/^\d+$/',$getuname)){
echo sprintf('%05d', $getuname);
}else{
// incorrect format
}
<?php
$getuname = $_GET['un'];
while (strlen($getuname) < 5) {
$getuname = '0' . $getuname;
}
echo $getuname;
?>
Related
I'm beginning in PHP or cakephp.
I have a case, when I want to get Just The Number in a code which type is string,
This is example string:
PR00006757
I want to get the number 00006757 without PR
I already tried using:
$code = filter_var($this->request->data['Price']['code'], FILTER_SANITIZE_NUMBER_INT);
pr ($code); exit;
then I get result "00006757",
But I want +1 that result,
to be "00006757 + 1" = 00006758,
But in reality, the result after I add 1 ( + 1) the result is 6758 not 00006758.
How do I get the answer formatted this way?
The output you are getting is correct as adding 1 automatically converts $code to integer type. You should use str_pad to pad the integer value you get by adding 1 to make it back to string of the required length.
$code = filter_var($this->request->data['Price']['code'], FILTER_SANITIZE_NUMBER_INT);
$code +=1;
$code = str_pad($code, 8, '0', STR_PAD_LEFT); //convert to padded string
print_r ($code);
Edit: Demo Here
Edit 2:
Added auto detection of the length
$code = filter_var($this->request->data['Price']['code'], FILTER_SANITIZE_NUMBER_INT);
$len = strlen($code); // store the length of the code
$code +=1;
$code = str_pad($code, $len, '0', STR_PAD_LEFT);
print_r ($code);
Demo Here
You're on the right track. Using filter_var is the correct way to grab the number you want. There isn't going to be a way to alter the way that PHP does basic addition. Your best chance is to identify the padding on the number and add that padding back after addition occurs. Here is an update to your code that could help.
$code = filter_var($this->request->data['Price']['code'], FILTER_SANITIZE_NUMBER_INT);
$len = strlen($code);
$newcode = $code + 1;
str_pad($newcode, $len, "0", STR_PAD_LEFT);
After testing with your example input I received: "00006758".
Here is another example
<?php
$str_code = 'PR00006757';
$code = filter_var($str_code, FILTER_SANITIZE_NUMBER_INT);
$code +=1;
$num_padded = sprintf("%08d", $code);
echo $num_padded;
I am making my first steps in PHP. The problems is I defined different types of variables, but the output shows their type as string.
Code
$firstname = 'Hosam';
$age = '22';
$height = '1.84';
$mobile = 'true';
echo $firstname . '<br/>';
echo gettype($firstname).'<br/>';
echo $age . '<br/>';
echo gettype($age).'<br/>';
echo $height . '<br/>';
echo gettype($height).'<br/>';
if ($mobile) {echo 'i9300'.'<br/>';}
else {echo 'Does not have smartphone'.'<br/>';}
echo gettype($mobile);
Output
Hosam
string
22
string
1.84
string
i9300
string
In PHP it's a string if you define it as so, until you do something that type juggles it, like add to it, or check it's truthyness.
You'll want to define them without the quotes, or cast them to explicitly change their type.
Read this for more information: http://php.net/manual/en/language.types.type-juggling.php
You have to remove the quotes from the numbers.
$firstname = 'Hosam';
$age = 22;
$height = 1.84;
$mobile = 'true';
any value that is in quotes is a string, even if its a number
so '22' is a string.
but 22 is a number.
And as Dan pointed out also. You will want to remove quotes around true, since true is not considered a string , unless you're actually wanting to like print the word true.
This is a tricky one: I want to add +1 to this number: 012345675901 and the expected result is: 012345675902. Instead I get: 2739134 when I do this:
echo (012345675901+1);
When I try:
echo ('012345675901'+1);
I get this: 12345675902 which is pretty close to what I need, but it removes the leading zero.
When I do this:
echo (int) 012345675901;
I get 2739133. I also tried bcadd() without success:
echo bcadd(012345675901, 1);
which resulted in 2739134.
I know I am missing something here. I would really appreciate your help!
UPDATE 1
Answer 1 says that the number is octal:
function is_octal($x) {
return decoct(octdec($x)) == $x;
}
$number = is_octal(012345675901);
echo var_dump($number);
The above returns false. I thought I needed to convert this from octal to a normal string but didn't work. I can't avoid not using the above number - I just need to increment it by one.
EDIT 2
This is the correct code:
$str = '012345675901';
$str1 = ltrim($str, '0'); // to remove the leading zero
$str2 = bcadd($str1, 1); // +1 to your result
$str3 = strlen($str); // get the length of your first number
echo str_pad($str2, $str3, '0', STR_PAD_LEFT); // apply zeros
Thank you everyone for your help! The above code produces: 012345675902 as expected
The leading 0 is treating your number as octal.
The leading 0 you need for output as a string, is a purely a representation.
please see the code for explanation.
$str = "012345675901"; // your number
$str1 = ltrim($str, '0'); // to remove the leading zero
$str2 = bcadd($str1, 1); // +1 to your result
$str3 = strlen($str); // get the length of your first number
echo str_pad($str2, $str3, '0', STR_PAD_LEFT); // apply zeros
I got a string value in number, like 2345.567, I want to keep only one character after the decimal. I dont want to use any Number function, I just want to remove any number of character after the period (dot)?
If you are worried about the input being not a number, you should validate it first:
function round_number($number, $precision = 1) {
if(!is_numeric($number)) {
throw new InvalidArgumentException("round_number() expects a numeric type, instead received '".gettype($number)."'");
}
return round($number, $precision);
}
Reference:
round($number, $precision)
is_numeric($var)
$number = 2345.567;
$new_numb = number_format($number,1);
$new_numb will be treated as string
<?php
$str = "2345.567";
$ip = explode('.',$str);
echo $ip[0].".".substr($ip[1],0,1)
?>
after edit:
<?php
// case: if there is no decimal place
echo $ip[0]."".($ip[1]?".".substr($ip[1],0,1):'');
?>
Formatted string output can be done with number_format or with the printf family of functions.
print number_format((float)$string, 1);
printf("%.1f", $string);
Assuming the input is guaranteed to be well-formed...
substr($numberString, 0, strpos(".", $numberString) + 2);
You can do it as follows
$string = "234567.2345";
if(!is_numeric($string)) {
$output = $string;
}
else{
$output = round($string,1);
}
output will be
234567.2
if string is given as 234
output will be 234.o
if string is given other than number "asdf"
output will be asdf
I need help converting a string that contains a number in scientific notation to a double.
Example strings:
"1.8281e-009"
"2.3562e-007"
"0.911348"
I was thinking about just breaking the number into the number on the left and the exponent and than just do the math to generate the number; but is there a better/standard way to do this?
PHP is typeless dynamically typed, meaning it has to parse values to determine their types (recent versions of PHP have type declarations).
In your case, you may simply perform a numerical operation to force PHP to consider the values as numbers (and it understands the scientific notation x.yE-z).
Try for instance
foreach (array("1.8281e-009","2.3562e-007","0.911348") as $a)
{
echo "String $a: Number: " . ($a + 1) . "\n";
}
just adding 1 (you could also subtract zero) will make the strings become numbers, with the right amount of decimals.
Result:
String 1.8281e-009: Number: 1.0000000018281
String 2.3562e-007: Number: 1.00000023562
String 0.911348: Number: 1.911348
You might also cast the result using (float)
$real = (float) "3.141592e-007";
$f = (float) "1.8281e-009";
var_dump($f); // float(1.8281E-9)
Following line of code can help you to display bigint value,
$token= sprintf("%.0f",$scienticNotationNum );
refer with this link.
$float = sprintf('%f', $scientific_notation);
$integer = sprintf('%d', $scientific_notation);
if ($float == $integer)
{
// this is a whole number, so remove all decimals
$output = $integer;
}
else
{
// remove trailing zeroes from the decimal portion
$output = rtrim($float,'0');
$output = rtrim($output,'.');
}
I found a post that used number_format to convert the value from a float scientific notation number to a non-scientific notation number:
Example from the post:
$big_integer = 1202400000;
$formatted_int = number_format($big_integer, 0, '.', '');
echo $formatted_int; //outputs 1202400000 as expected
Use number_format() and rtrim() functions together. Eg
//eg $sciNotation = 2.3649E-8
$number = number_format($sciNotation, 10); //Use $dec_point large enough
echo rtrim($number, '0'); //Remove trailing zeros
I created a function, with more functions (pun not intended)
function decimalNotation($num){
$parts = explode('E', $num);
if(count($parts) != 2){
return $num;
}
$exp = abs(end($parts)) + 3;
$decimal = number_format($num, $exp);
$decimal = rtrim($decimal, '0');
return rtrim($decimal, '.');
}
function decimal_notation($float) {
$parts = explode('E', $float);
if(count($parts) === 2){
$exp = abs(end($parts)) + strlen($parts[0]);
$decimal = number_format($float, $exp);
return rtrim($decimal, '.0');
}
else{
return $float;
}
}
work with 0.000077240388
I tried the +1,-1,/1 solution but that was not sufficient without rounding the number afterwards using round($a,4) or similar