This question already has answers here:
Get the sum of all digits in a numeric string
(13 answers)
Closed 8 months ago.
I'm trying to adding all numbers from last 6 digit from substr(). Let say the number is 19283774616, I'm trying to have result from this: 7+7+4+6+1+6 = ?. Here is my current code
public function accountHash($accountNumber)
{
$result = 0;
$accountNumber = substr($accountNumber, -6);
for($i=0; $i<=strlen($accountNumber); $i++) {
$result += substr($accountNumber, $i, 1); // A non-numeric value encountered here
}
echo $result;
}
From the function above, "A non-numeric value encountered" error occurred. Need suggestion on how to do this. Thank you
You attempt to get more characters than string contains. Replace "<=" with "<" in your condition expression, i.e. change:
for($i=0; $i<=strlen($accountNumber); $i++) {
to
for($i=0; $i<strlen($accountNumber); $i++) {
You need to use < instead of <= in your for loop.
And you can do it a more simple way,
$result = 0;
for($i = 0; $i < 6; $i++){
$result += $string[-$i];
}
An alternative method without loops (or error checking, for what it's worth):
function accountHash($accountNumber)
{
return array_sum(
preg_split('//u', mb_substr($accountNumber, -6), null, PREG_SPLIT_NO_EMPTY)
);
}
Demo
Related
This question already has answers here:
PHP: How to sort the characters in a string?
(5 answers)
Closed 2 years ago.
we are trying to reorder the number
for example
5695479 to 9976554
48932 to 98432
means all bigger numbers then smaller number.
i was searching for some inbuilt function in php, we found sort function can do with array.
$numbers=array(4,6,2,22,11);
sort($numbers);
function my_sort($a,$b)
{
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}
$a=array(4,2,8,6);
usort($a,"my_sort");
i have searched lot but i could not found any inbuilt functions.
There is no specific in-built function for this. However, you can use more than 1 inbuilt function to accomplish your task.
You can convert the integer to string usingstrval.
Now, split the string by each digit to get an array of integers.
Apply rsort() to sort them in descending order.
Implode() them back to get the number you desire.
Snippet:
<?php
$str = strval(5695479);
$nums = str_split($str);
rsort($nums);
echo implode("",$nums);
Another alterantive is to use counting sort for digits. Since digits will always be between 0-9, collect their count and loop from 9 to 0 and get the new number. This method would be faster than the first method if you have the number in string format with huge lengths.
Snippet:
<?php
$num = 48932; // if number is in string format, loop char by char using for loop
$count = [];
while($num > 0){
if(!isset($count[$num % 10])) $count[$num % 10] = 0;
$count[$num % 10]++;
$num = intval($num / 10);
}
$new_num = 0;
for($i = 9; $i >=0; --$i){
if(!isset($count[$i])) continue;
while($count[$i]-- > 0) $new_num = $new_num * 10 + $i; // you would rather concatenate here incase of string.
}
echo $new_num;
This question already has answers here:
Break long string into pieces php
(5 answers)
Closed 3 years ago.
I want to make a program which splits a long number into pieces of 13 digited number such that I can loop for every 13 digits just using php.
$number = 012345678901230123456789123
Should output
0123456789123
0123456789123
And it should be for any large number having the number of digit multiple of 13.It looks about looping and algorithm but I want to make it as short as possible and I have doubts on how to do it. So I am just asking about the main concept.
The most dynamic solution is probably to use array_functions on the string.
So str_split to make it array then chunk it in size 13 and implode the arrays.
$number = "012345678901230123456789123";
$arr = array_chunk(str_split($number), 13);
foreach($arr as &$val){
$val = implode($val);
}
https://3v4l.org/LsNFt
You can create a function where you can use your string and size as parameter and return an array of strings of the desired length:
function splitString($str, $packetSize) {
$output = [];
$size = strlen($str);
for ($i = 0; $i < $size; $i += $packetSize) {
if ($i + $packetSize < $size) {
$output[]= substr($str, $i, $packetSize);
} else {
$output[]=substr($str, $i);
}
}
return $output;
}
This question already has answers here:
Get last whole number in a string
(7 answers)
Closed 6 months ago.
I have this string #22aantal283xuitvoeren.
What is the best way to find the last numeric value in a string? (283 in this case)
I don't think chop() or substr() is the wat to go.
You can use preg_match_all and match all digits.
Then the last item in the array is the last number in the string.
$s = "#22aantal283xuitvoeren";
preg_match_all("/\d+/", $s, $number);
echo end($number[0]); // 283
https://3v4l.org/44VUJ
You could try preg_match_all():
$string = "#22aantal283xuitvoeren";
$result = preg_match_all(
"/(\d+)/",
$string,
$matches);
$lastNumericValueInString = array_pop($matches[1]);
echo $lastNumericValueInString;
Echoes 283
Here is a solution without regex.
Basically loop from back to front until the first number is found. Then, loop until the first non-number is found.
$string = "#22aantal283xuitvoeren";
for($i = strlen($string) - 1; $i >= 0; --$i) {
if(is_numeric($string[$i])) {
// found the first number from back to front
$number = $string[$i];
while(--$i >= 0 && is_numeric($string[$i])) {
$number = $string[$i].$number;
}
break;
}
}
// $number is now "283"
// if you want an integer, use intval($number)
This question already has answers here:
Formatting a number with leading zeros in PHP [duplicate]
(11 answers)
Closed 7 years ago.
I would like to Increment numbers with double digits if the number is less then 10
This is what i tried so far
$i = 1;
echo $i++;
results is 1,2,3,4,5,6 so on
Then i try adding a condition
$i = 1;
if ($i++<10){
echo "0".$i++;
}else{
echo $i++;
}
Work but skipping the numbers 2,4,6,8 so on.
Can anyone tell me the proper way to do this?
If the condition is only there for the leading zero you can do this much easier with this:
<?php
$i = 10;
printf("%02d", $i++);
?>
if you want prepend something to a string use:
echo str_pad($input, 2, "0", STR_PAD_LEFT); //see detailed information http://php.net/manual/en/function.str-pad.php
On the second fragment of code you are incrementing $i twice, that's why you get only even numbers.
Incrementing a number is one thing, rendering it using a specific format is another thing. Don't mix them.
Keep it simple:
// Increment $i
$i ++;
// Format it for display
if ($i < 10) {
$text = '0'.$i; // Prepend values smaller than 10 with a zero
} else {
$text = $i;
}
// Display it
echo($text);
<?php
$i = 1;
for($i=1;$i<15;){
if($i<10){
echo '0'.$i++."<br>";
}else{
echo $i++."<br>";
}
}
?>
This question already has answers here:
Closed 12 years ago.
The community reviewed whether to reopen this question 10 months ago and left it closed:
Original close reason(s) were not resolved
Possible Duplicate:
Check if a String Ends with a Number in PHP
I'm trying to implement the function below. Would it be best to use some type of regex here? I need to capture the number too.
function startsWithNumber($string) {
$startsWithNumber = false;
// Logic
return $startsWithNumber;
}
You can use substr and ctype_digit:
function startsWithNumber($string) {
return strlen($string) > 0 && ctype_digit(substr($string, 0, 1));
}
The additional strlen is just required as ctype_digit returns true for an empty string before PHP 5.1.
Or, if you rather want to use a regular expression:
function startsWithNumber($str) {
return preg_match('/^\d/', $str) === 1;
}
Something like to this may work to you:
function str2int($string) {
$length = strlen($string);
for ($i = 0, $int = ''; $i < $length; $i++) {
if (is_numeric($string[$i]))
$int .= $string[$i];
else break;
}
return (int) $int;
}