PHP: Using str_pad not working? Why? - php

I have a string, its content is "24896". Now I want to add some zeros to the left, so I tried:
$test = str_pad($myString, 4, "0", STR_PAD_LEFT);
The result is "24896" again, no zeros added to the left. Am I missing something here?
Thanks!

The second argument to str_pad() takes the full length of the final string; because you're passing 4 and the length of $myString is 5, nothing will happen.
You should choose a width that's at least one bigger than your example value, e.g.:
str_pad($myString, 9, '0', STR_PAD_LEFT);
// "000024896"
Update
This might be obvious, but if you always want 4 zeros in front of whatever $myString is:
'0000' . $myString;

Because you're padding it to length 4, and your string 24896 is 5 characters long, hence it doesn't need to pad anything as it's already more than 4 characters long.
The second parameter in the str_pad function is the new length of the string.

Try
$myString = "24896" ;
$test = str_pad($myString, strlen($myString) + 4, "0", STR_PAD_LEFT);
echo $test;
Output
000024896

Just make the pad first and attach it, presuming you don't know how long it is. No need to calculate the length of the original string:
$x = 4;
$pad = str_pad('', $x, '0');
$test = $pad.$myString;
Or better
$x = 4;
$test = str_pad('', $x, '0').$myString;

The length you specified in the str_function is less than the input string read documentation properly
try this it will work for you
Your String is 5 character
e.g $myString=24896;
Now you want to add 5 zero to the left
then your length will be you string + 5 the actual is 5+5=10;
Now pass this to the function your function will be like this
$test = str_pad($myString, 10, "0", STR_PAD_LEFT);
echo $test;
OUTPUT:
0000024896

how many no zero you want to add? no zeros added because padding length is smaller than your given $myString length.
Please try this one
$number = 24896;
$number = sprintf('%06d', $number);
echo $number;
or use this one
$number = 24896;
$number = str_pad($number, 6, '0', STR_PAD_LEFT);//here 6 is padding length
echo $number;
output
024896

Related

php math plus don't remove zeros

PLease look my php code. I dont want rmeoving zeros.
<?php
$number = '00154';
$next = $number + 1;
echo $next; // returns 155
?>
But I want to return 00155
Use str_pad() in conjunction with strlen(). strlen() gets the number of digits, and then uses that as the pad length for str_pad().
$next = str_pad($next, strlen($number), '0', STR_PAD_LEFT);
If you always want a fixed length, say 5, then this becomes shorter:
$next = sprintf('%05d', $next);
Demo
You can do that with str_pad if your number length is constant. In your case you have 5 length number. You can get length of number first and you can fill up zeros in result;
<?php
$number = '00154';
$length = strlen($number);
$next = $number + 1;
echo str_pad($next, $length, "0", STR_PAD_LEFT);
?>
Here is a working demo: codepad
00155 and 155 is from a maths perspective EQUAL.
echo str_pad($next, 5, '0', STR_PAD_LEFT);
fills left side with zeroes.
This is because your number is a string. Convert it to a number (integer or float) first, the use math function.

PHP add thousand separators to number and keep leading zeros

I'm trying to add thousand separators to a number using PHP and at the same time keep the leading zeros (It's part of the design of an app that the leading 0s stay so that people can see the number grow towards the set target - a 6 figure number).
My initial attempt was to use str_pad to add the leading zeros if the current number calculated was less than 6 figures long. Then to add the commas I used number_format. The obvious issue is that number_format removes the leading 0s.
$num = 550;
$num_padded = str_pad($num, 6, '0', STR_PAD_LEFT);
echo number_format($num_padded);
So that returns 550 instead of 000,550
Does anyone know of a reliable way to achieve the format I'm looking for?
Thanks!
I have in mind this simple trick:
function padAndFormat($number, $length)
{
if(strlen($number)>=$length)
{
return number_format($number);
}
$number = number_format('1'.str_pad($number, $length-1, '0', STR_PAD_LEFT));
$number[0] = '0';
return $number;
}
//var_dump(padAndFormat('517', 6)); //string(7) "000,517"
another way to do this is to use sprintf
// length can be changed, here is 6
implode(',',str_split(sprintf('%06d', $this->iterator),3));
the result will be :
input
result
4
000,004
400
000,400
23560
023,560
1234567
1,234,567
it can be improved by reading the length, and computing automatically the final length, multiple of 3
I don't need number format but I need that comma! :)
<?php
$zeroes=0;
$num = 550;
$num_padded = str_pad($zeroes, 3, '0', STR_PAD_LEFT);
$num_padded = str_pad($num_padded,strlen($num_padded)+strlen($zeroes), ',', STR_PAD_RIGHT);
$num_padded = str_pad($num_padded,strlen($num_padded)+strlen($num), $num, STR_PAD_RIGHT);
echo $num_padded;
OUTPUT :
000,550
One Liner with PHP string manipulation. Works for any number of digits:
function pad($number, $min_digits){
return strrev(implode(",",str_split(str_pad(strrev($number), $min_digits, "0", STR_PAD_RIGHT),3)));
}
/* Output for 9 digits
0,000,001
0,000,012
0,000,123
0,001,234
0,012,345
0,123,456
1,234,567
12,345,678
123,456,789
/**/

PHP increase number by one

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

function to return the numeric value

What would be an elegant way of doing this?
I have this -> "MC0001" This is the input. It always begins with "MC"
The output I'd be aiming with this input is "MC0002".
So I've created a function that's supposed to return "1" after removing "MC000". I'm going to convert this into an integer later on so I could generate "MC0002" which could go up to "MC9999". To do that, I figured I'd need to loop through the string and count the zeros and so on but I think I'd be making a mess that way.
Anybody has a better idea?
This should do the trick:
<?php
$string = 'MC0001';
// extract the part succeeding 'MC':
$number_part = substr($string, 2);
// count the digits for later:
$number_digits = strlen($number_part);
// turn it into a number:
$number = (int) $number_part;
// make the next sequence:
$next = 'MC' . str_pad($number + 1, $number_digits, '0', STR_PAD_LEFT);
using filter_var might be the best solution.
echo filter_var("MC0001", FILTER_SANITIZE_NUMBER_INT)."\n";
echo filter_var("MC9999", FILTER_SANITIZE_NUMBER_INT);
will give you
0001
9999
These can be cast to int or just used as they are, as PHP will auto-convert anyway if you use them as numbers.
just use ltrim to remove any leading chars: http://php.net/manual/en/function.trim.php
$str = ltrim($str, 'MC0');
$num = intval($str);
<php
// original number to integer
sscanf( $your_string, 'MC%d', $your_number );
// pad increment to string later on
sprintf( 'MC%04u', $your_number + 1 );
Not sure if there is a better way of parsing a string as an integer when there are leading zero's.
I'd suggest doing the following:
1. Loop through the string ( beginning at location 2 since you don't need the MC part )
2. If you find a number thats bigger than 0, stop, get the substring using your current location and the length of the string minus your current location. Cast to integer, return value.
You can remove the "MC" par by doing a substring operating on the string.
$a = "MC0001";
$a = substr($a, 2); //Lengths of "MC"
$number = intval($a); //1
return intval(str_replace($input, 'MC', ''), 10);

Incrementing numbers starting from 0000 in php

I need a suggestion on a function for a php counter. Is there any function to have numbers with 5 digit as 00001, or 00123… this number should be not random but have to increase the value of a previous field.
If a number is $n=’00001’ there is a function to increase by one and get 00002 and not 2?
Thanks
F.
$n2 = str_pad($n + 1, 5, 0, STR_PAD_LEFT);
Use str_pad() by adding 0s (third parameter) to the left (fourth parameter) of the old number $n incremented by 1 (first parameter) until the length is 5 (second parameter).
$number = 1;
$number++;
echo str_pad($number, 5, "0", STR_PAD_LEFT); //00002
As an alternative, in case you are interested, you can use sprintf to pad this with 0's up to a certain number fairly easily.
$numbers = array(0,1,11,111,1111,11111,11111);
$padded = array();
foreach($numbers as $num)
$padded[] = sprintf('%1$05d', ++$num);
print_r($padded);
PHP almost always has numerous ways to do the same thing. :)
You need the str_pad() function to add leading zeros to your indexes.
$new_index = str_pad($index, 5, "0", STR_PAD_LEFT);
Where $index your incrementing index in circle, $new_index is your index with leading zeros.

Categories