Adding a string and an integer in php - php

I'm trying to add a 1 in front of my binary code and this is how I'm going about it:
if I have 0101, for example, then I'd add a number with 4 zeroes, like 10000 so it would become 10101. Here's my code:
$fill = strlen($string);
$number = '1';
$add = str_pad($number, $fill, '0', STR_PAD_RIGHT);
$m1 = $string + $add;
The problem is the output for that is something like 1.random number e+Random number

assuming $string is your "0101" string, you could just do $m1 = '1'.$string;

My previous answer was wrong because the length of the string is potentially variable and str_pad requires you to know the length. This will work, but it doesn't look so elegant:
if (strpos($string, '0') === 0) {
$string = '1' . $string;
}

Related

Trim zeros from decimal part php

My exact requirement is, if the second decimal of the value is zero,
the value should only have one decimal. For others, it should have two decimal.
eg 1. 150.00 to 150.0
eg 2. 150.10 to 150.1
eg 3. 150.76 to 150.76
What I need to know is whether there is any PHP function to do this.
echo floatval("150.00")."<br>";
echo floatval("150.10")."<br>";
echo floatval("150.76")."<br>";
The result is as follows:
150
150.1
150.76
I need to have 150.0 instead of 150. I just need to know if there is any php function. Otherwise I will be able to write code.
You can use substr() function also to remove last char if it is 0. May be the below code will help you
function roundit($string)
{
$string = number_format($string,2);
if (substr($string, -1, 1) == '0')
{
$string = substr($string, 0, -1);
echo $string;
}
else
echo $string;
}
roundit('150.00');
roundit('150.10');
roundit('150.76');
You may write a simple function to help you out with that. Something like this could do the trick:
<?php
function removeTrailingZero($num){
$num = floatval($num);
$pieces = explode(".", $num);
for($i=0; $i<count($pieces); $i++){
if(isset($pieces[1])){
$pieces[1] = preg_replace("#0*$#", "", $pieces[1]);
break;
}else{
$pieces[1] = '0';
break;
}
}
return rtrim(implode(".", $pieces), ".");
//return floatval(rtrim(implode(".", $pieces), "."));
}
var_dump(removeTrailingZero(123.45));
var_dump(removeTrailingZero(67.80));
var_dump(removeTrailingZero(90));
var_dump(removeTrailingZero(100.00000));
// PRODUCES:::
string '123.45' (length=6)
string '67.8' (length=4)
string '90.0' (length=4)
string '100.0' (length=5)

PHP - For Loop Keep Significant Digits [duplicate]

This question already has answers here:
Zero-pad digits in string
(5 answers)
Closed 2 years ago.
I have a variable which contains the value 1234567.
I would like it to contain exactly 8 digits, i.e. 01234567.
Is there a PHP function for that?
Use sprintf :
sprintf('%08d', 1234567);
Alternatively you can also use str_pad:
str_pad($value, 8, '0', STR_PAD_LEFT);
Given that the value is in $value:
To echo it:
printf("%08d", $value);
To get it:
$formatted_value = sprintf("%08d", $value);
That should do the trick
When I need 01 instead of 1, the following worked for me:
$number = 1;
$number = str_pad($number, 2, '0', STR_PAD_LEFT);
echo str_pad("1234567", 8, '0', STR_PAD_LEFT);
sprintf is what you need.
EDIT (somehow requested by the downvotes), from the page linked above, here's a sample "zero-padded integers":
<?php
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?>
Though I'm not really sure what you want to do you are probably looking for sprintf.
This would be:
$value = sprintf( '%08d', 1234567 );
Simple answer
$p = 1234567;
$p = sprintf("%08d",$p);
I'm not sure how to interpret the comment saying "It will never be more than 8 digits" and if it's referring to the input or the output. If it refers to the output you would have to have an additional substr() call to clip the string.
To clip the first 8 digits
$p = substr(sprintf('%08d', $p),0,8);
To clip the last 8 digits
$p = substr(sprintf('%08d', $p),-8,8);
If the input numbers have always 7 or 8 digits, you can also use
$str = ($input < 10000000) ? 0 . $input : $input;
I ran some tests and get that this would be up to double as fast as str_pad or sprintf.
If the input can have any length, then you could also use
$str = substr('00000000' . $input, -8);
This is not as fast as the other one, but should also be a little bit faster than str_pad and sprintf.
Btw: My test also said that sprintf is a little faster than str_pad. I made all tests with PHP 5.6.
Edit: Altough the substr version seems to be still very fast (PHP 7.2), it also is broken in case your input can be longer than the length you want to pad to. E.g. you want to pad to 3 digits and your input has 4 than substr('0000' . '1234', -3) = '234' will only result in the last 3 digits
$no_of_digit = 10;
$number = 123;
$length = strlen((string)$number);
for($i = $length;$i<$no_of_digit;$i++)
{
$number = '0'.$number;
}
echo $number; /////// result 0000000123
I wrote this simple function to produce this format: 01:00:03
Seconds are always shown (even if zero).
Minutes are shown if greater than zero or if hours or days are required.
Hours are shown if greater than zero or if days are required.
Days are shown if greater than zero.
function formatSeconds($secs) {
$result = '';
$seconds = intval($secs) % 60;
$minutes = (intval($secs) / 60) % 60;
$hours = (intval($secs) / 3600) % 24;
$days = intval(intval($secs) / (3600*24));
if ($days > 0) {
$result = str_pad($days, 2, '0', STR_PAD_LEFT) . ':';
}
if(($hours > 0) || ($result!="")) {
$result .= str_pad($hours, 2, '0', STR_PAD_LEFT) . ':';
}
if (($minutes > 0) || ($result!="")) {
$result .= str_pad($minutes, 2, '0', STR_PAD_LEFT) . ':';
}
//seconds aways shown
$result .= str_pad($seconds, 2, '0', STR_PAD_LEFT);
return $result;
} //funct
Examples:
echo formatSeconds(15); //15
echo formatSeconds(100); //01:40
echo formatSeconds(10800); //03:00:00 (mins shown even if zero)
echo formatSeconds(10000000); //115:17:46:40
You can always abuse type juggling:
function zpad(int $value, int $pad): string {
return substr(1, $value + 10 ** $pad);
}
This wont work as expected if either 10 ** pad > INT_MAX or value >= 10 * pad.

Finding a character at a specific position of a string

Since I am still new to PHP, I am looking for a way to find out how to get a specific character from a string.
Example:
$word = "master";
$length = strlen($word);
$random = rand(1,$length);
So let's say the $random value is 3, then I would like to find out what character the third one is, so in this case the character "s". If $random was 2 I would like to know that it's a "a".
I am sure this is really easy, but I tried some substr ideas for nearly an hour now and it always fails.
Your help would be greatly appreciated.
You can use substr() to grab a portion of a string starting from a point and going length. so example would be:
substr('abcde', 1, 1); //returns b
In your case:
$word = "master";
$length = strlen($word) - 1;
$random = rand(0,$length);
echo substr($word, $random, 1);//echos single char at random pos
See it in action here
You can use your string the same like 0-based index array:
$some_string = "apple";
echo $some_string[2];
It'll print 'p'.
or, in your case:
$word = "master";
$length = strlen($word);
$random = rand(0,$length-1);
echo $word[$random];
Try this simply:
$word = "master";
$length = strlen($word);
$random = rand(0,$length-1);
if($word[$random] == 's'){
echo $word[$random];
}
Here I used 0 because $word[0] is m so that we need to subtract one from strlen($word) for getting last character r
Use substr
$GetThis = substr($myStr, 5, 5);
Just use the same values for the same or different if you want multiple characters
$word = "master";
$length = strlen($word);
$random = rand(0,$length-1);
$GetThis = substr($word, $random, $random);
As noted in my comment (I overlooked as well) be sure to start your rand at 0 to include the beginning of your string since the m is at place 0. If we all overlooked that it wouldn't be random (as random?) now would it :)
You can simply use $myStr{$random} to obtain the nth character of the string.

Replacing last x amount of numbers

I have a PHP variable that looks a bit like this:
$id = "01922312";
I need to replace the last two or three numbers with another character. How can I go about doing this?
EDIT Sorry for the confusion, basically I have the variable above, and after I'm done processing it I'd like for it to look something like this:
$new = "01922xxx";
Try this:
$new = substr($id, 0, -3) . 'xxx';
Result:
01922xxx
You can use substr_replace to replace a substring.
$id = substr_replace($id, 'xxx', -3);
Reference:
http://php.net/substr-replace
function replaceCharsInNumber($num, $chars) {
return substr((string) $num, 0, -strlen($chars)) . $chars;
}
Usage:
$number = 5069695;
echo replaceCharsInNumber($number, 'xxx'); //5069xxx
See it in action here: http://codepad.org/XGyVQ1hk
Strings can be treated as arrays, with the characters being the keys:
$id = 1922312; // PHP converts 01922312 => 1 because of that leading zero. Either make it a string or remove the zero.
$id_str = strval($id);
for ($i = 0; $i < count($id_str); $i++)
{
print($id_str[$i]);
}
This should output your original number. Now to do stuff with it, treat it as a normal array:
$id_str[count($id_str) - 1] = 'x';
$id_str[count($id_str) - 2] = 'y';
$id_str[count($id_str) - 3] = 'z';
Hope this helps!
Just convert to string and replace...
$stringId = $id . '';
$stringId = substr($id, 0, -2) . 'XX';
We can replace specific characters in a string using preg_replace(). In my case, I want to replace 30 with 50 (keep the first two digits xx30), in the $start_time which is '1030'.
Solution:
$start_time = '1030';
$pattern = '/(?<=\d\d)30/';
$start_time = preg_replace($pattern, '50', $start_time);
//result: 1050

Formatting a number with leading zeros in PHP [duplicate]

This question already has answers here:
Zero-pad digits in string
(5 answers)
Closed 2 years ago.
I have a variable which contains the value 1234567.
I would like it to contain exactly 8 digits, i.e. 01234567.
Is there a PHP function for that?
Use sprintf :
sprintf('%08d', 1234567);
Alternatively you can also use str_pad:
str_pad($value, 8, '0', STR_PAD_LEFT);
Given that the value is in $value:
To echo it:
printf("%08d", $value);
To get it:
$formatted_value = sprintf("%08d", $value);
That should do the trick
When I need 01 instead of 1, the following worked for me:
$number = 1;
$number = str_pad($number, 2, '0', STR_PAD_LEFT);
echo str_pad("1234567", 8, '0', STR_PAD_LEFT);
sprintf is what you need.
EDIT (somehow requested by the downvotes), from the page linked above, here's a sample "zero-padded integers":
<?php
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?>
Though I'm not really sure what you want to do you are probably looking for sprintf.
This would be:
$value = sprintf( '%08d', 1234567 );
Simple answer
$p = 1234567;
$p = sprintf("%08d",$p);
I'm not sure how to interpret the comment saying "It will never be more than 8 digits" and if it's referring to the input or the output. If it refers to the output you would have to have an additional substr() call to clip the string.
To clip the first 8 digits
$p = substr(sprintf('%08d', $p),0,8);
To clip the last 8 digits
$p = substr(sprintf('%08d', $p),-8,8);
If the input numbers have always 7 or 8 digits, you can also use
$str = ($input < 10000000) ? 0 . $input : $input;
I ran some tests and get that this would be up to double as fast as str_pad or sprintf.
If the input can have any length, then you could also use
$str = substr('00000000' . $input, -8);
This is not as fast as the other one, but should also be a little bit faster than str_pad and sprintf.
Btw: My test also said that sprintf is a little faster than str_pad. I made all tests with PHP 5.6.
Edit: Altough the substr version seems to be still very fast (PHP 7.2), it also is broken in case your input can be longer than the length you want to pad to. E.g. you want to pad to 3 digits and your input has 4 than substr('0000' . '1234', -3) = '234' will only result in the last 3 digits
$no_of_digit = 10;
$number = 123;
$length = strlen((string)$number);
for($i = $length;$i<$no_of_digit;$i++)
{
$number = '0'.$number;
}
echo $number; /////// result 0000000123
I wrote this simple function to produce this format: 01:00:03
Seconds are always shown (even if zero).
Minutes are shown if greater than zero or if hours or days are required.
Hours are shown if greater than zero or if days are required.
Days are shown if greater than zero.
function formatSeconds($secs) {
$result = '';
$seconds = intval($secs) % 60;
$minutes = (intval($secs) / 60) % 60;
$hours = (intval($secs) / 3600) % 24;
$days = intval(intval($secs) / (3600*24));
if ($days > 0) {
$result = str_pad($days, 2, '0', STR_PAD_LEFT) . ':';
}
if(($hours > 0) || ($result!="")) {
$result .= str_pad($hours, 2, '0', STR_PAD_LEFT) . ':';
}
if (($minutes > 0) || ($result!="")) {
$result .= str_pad($minutes, 2, '0', STR_PAD_LEFT) . ':';
}
//seconds aways shown
$result .= str_pad($seconds, 2, '0', STR_PAD_LEFT);
return $result;
} //funct
Examples:
echo formatSeconds(15); //15
echo formatSeconds(100); //01:40
echo formatSeconds(10800); //03:00:00 (mins shown even if zero)
echo formatSeconds(10000000); //115:17:46:40
You can always abuse type juggling:
function zpad(int $value, int $pad): string {
return substr(1, $value + 10 ** $pad);
}
This wont work as expected if either 10 ** pad > INT_MAX or value >= 10 * pad.

Categories