PHP increase number by one - php

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

Related

Replacing First 4 digits of a 10 digit number with x

I'm trying to replace the first 4 digits of a number with X, for example:
$num= 1234567890
I want the output to appear like this: XXXX567890
I have tried the function:
$new = substr($num, 0, -4) . 'xxx';
but It only removes the last 4 digits so what should I do ?
You can use the same in opposite
$num= 1234567890;
$new = 'xxxx' . substr($num, 4);
echo $new;
second parameter tells about starting point for string and parity(positive or negative) tells about direction. positive number means to right of string and negative number means to left of string.
http://php.net/manual/en/function.substr.php
With substr_replace function:
$num = 1234567890;
print_r(substr_replace($num, 'XXXX', 0, 4)); // XXXX567890
Another solution is to use str_pad which "fills up" the string to 10 elements with "X".
$num= 1234567890;
Echo str_pad(substr($num,4), 10, "X",STR_PAD_LEFT);
https://3v4l.org/tKtB7
Or if the string lenght is not always 10 use:
Echo str_pad(substr($num,4), strlen($num), "X",STR_PAD_LEFT);
I think this one can be helpful for achieving desired output.
Solution 1:
Try this code snippet here
<?php
ini_set('display_errors', 1);
$num= 1234567890;
echo "XXXX".substr($num, 4);//concatenating 4 X and with the substring
Solution 2: Try this code snippet here
<?php
ini_set('display_errors', 1);
$num= 1234567890;
$totalDigits=4;
echo str_repeat("X", $totalDigits).substr($num, $totalDigits);// here we are using str_repeat to repeat a substring no. of times
Output: XXXX567890
If have written a tiny function to do tasks like this.
function hide_details($str, $num = 4, $replace = 'x') {
return str_repeat($replace, $num).substr($str, $num);
}
echo hide_details('1234567890');

How do I get the first and the last digit of a number in PHP?

How can I get the first and the last digit of a number? For example 2468, I want to get the number 28. I am able to get the ones in the middle (46) but I can't do the same for the first and last digit.
For the digits in the middle I can do it
$substrmid = substr ($sum,1,-1); //my $sum is 2468
echo $substrmid;
Thank you in advance.
You can get first and last character from string as below:-
$sum = (string)2468; // type casting int to string
echo $sum[0]; // 2
echo $sum[strlen($sum)-1]; // 8
OR
$arr = str_split(2468); // convert string to an array
echo reset($arr); // 2
echo end($arr); // 8
Best way is to use substr described by Mark Baker in his comment,
$sum = 2468; // No need of type casting
echo substr($sum, 0, 1); // 2
echo substr($sum, -1); // 8
You can use substr like this:
<?php
$a = 2468;
echo substr($a, 0, 1).substr($a,-1);
You can also use something like this (without casting).
$num = 2468;
$lastDigit = abs($num % 10); // 8
However, this solution doesn't work for decimal numbers, but if you know that you'll be working with nothing else than integers, it'll work.
The abs bit is there to cover the case of negative integers.
$num = (string)123;
$first = reset($num);
$last = end($num);

Can't get str_pad() to properly replace characters in a string

I'm trying to replace some characters from a string using str_pad and I can't get it to work at all and I have no idea why it doesn't work.
Code:
<?php
$t = "abcdefghij";
$t = str_pad($t, 4, "0");
echo $t;
?>
Expected:
abcd000000
Result:
abcdefghij
I also tried:
$t = sprintf("%04x", $t);
Which results in:
0000
If you have a variable length string, you can use the below
$str = "abcdefghijzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";
$head = substr($str, 0, 4); // construct the first part of your string
$tail = substr($str, 4); // get the second part of the string
print $head . str_repeat('0',strlen($tail));
// or all in one go
$number = 4;
print substr($str, 0, $number) . str_repeat('0',strlen(substr($str, $number)));
//will output
//abcd0000000000000000000000000000000000000
To replace everything except the first x number of characters in your string.
Because your string is longer than four characters so str_pad() will not append anything to it.
If the value of pad_length is negative, less than, or equal to the length of the input string, no padding takes place, and input will be returned.
If you want to always append four zeros just concatenate them onto your string:
<?php
$t = "abcdefghij";
$t = '0000' . $t;
echo $t;
?>
What you are looking for is a mixture of str_pad and substr, using the two like this:
echo str_pad(substr($str, 0, 4), strlen($str), '0', STR_PAD_RIGHT);
Will give you output like this:
abcd000000
You may however, need to tweak the numbers to get your desired results.
Here is a function you can use:
function pad($str, $length, $value= '0', $side = STR_PAD_RIGHT){
return str_pad(substr($str, 0, $length), strlen($str), $value, $side);
}
echo pad('abcdefghij', 4);
You need a different functions. str_pad() adds to the string and you are wanting to replace:
$t = substr_replace($t, str_repeat('0', strlen($t)-4), 4);

PHP: Using str_pad not working? Why?

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

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);

Categories