This question already has answers here:
Get the sum of all digits in a numeric string
(13 answers)
Closed 5 years ago.
I am getting o/p like "11111" and I want to sum all these digits that should become 5. But if I use count count it is showing one only i.e, 1.Rather it should show 5.
Below is my code,
$count = count($inventory['product_id']);
$product_total = $count;
echo $product_total;//o/p => 1.
I need echo $product_total;//o/p => 5.
You can use the following using str_split to get an array with all characters (in your case digits) and using array_sum to get the sum of all the digits:
$digits = "11112";
$arrDigits = str_split($digits);
echo array_sum($arrDigits); //6 (1 + 1 + 1 + 1 + 2)
Demo: https://ideone.com/tZwi9J
Count is used for counting array elements.
What you can do in PHP, is to iterate over a string using either a foreach (not 100% sure) or for loop for this and accessing the elements like array elements by their index:
$str = '111111123545';
$sum = 0;
for ($i = 0; $i < strlen($str); $i++) {
$sum += intval($str[$i]);
}
print $sum; // prints 26
Alternativly, you can split the string using no delimiter and using the array_sum() function on it:
$str = '111111123545';
$sum = array_sum(str_split($str));
print $sum; // prints 26
array_sum(str_split($number));
Another possible way to count the list of digits in PHP is:
// match only digits, returns counts
echo preg_match_all( "/[0-9]/", $str, $match );
// sum of digits
echo array_sum($match[0]);
Example:
$ php -r '$str="s12345abas"; echo "Count :".preg_match_all( "/[0-9]/", $str, $match ).PHP_EOL; echo "Sum :".array_sum($match[0]).PHP_EOL;'
Count :5
Sum :15
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:
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
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:
What is the most efficient way to count all the occurrences of a specific character in a PHP string?
(4 answers)
Closed 5 years ago.
I am trying to separate 2 symbols from a string and then
count how many of these symbols there are.
So if i had : 1110001110000
Then it should find that there are 6= 1's and 7= 0's
So This is what I have tried:
Essentially what I need, is to read the string indexes in code would be string[$i] then IF there is a 1 or a 0 count it.
I tried using a for-loop
for ($i=0; $i < $getInput[$i] ; $i++) {
if ($getInput[$i] == 1) {
echo "ONE";
} elseif ($getInput[$i] == 0) {
echo "ZERO";
}
}
Here im trying to echo out ONE for everytime ther is a 1 and ZERO for everytime theres a zero.
$counter = 0;
foreach ($getInput as $key) {
echo $key;
}
here i tried to utilize a foreach, here I am not really declaring to see for One index, i tried putting a for each in a for but needless to say, it didn't work.
Using substr_count, you can do this in a fairly straightforward way:
echo substr_count("1110001110000", '1'); //Echos 6
echo substr_count("1110001110000", '0'); //Echos 7
Substr_count.
http://php.net/manual/en/function.substr-count.php
$str = "1110001110000";
Echo "there is " .substr_count($str, "0") ." zeros \n";
Echo "there is " .substr_count($str, "1") ." ones \n";
https://3v4l.org/BQEiR
If you want to output it as your code implies (one one one zero) you can use numberformatter.
Here I split the string to an array and loop through it and output the spellout of each number.
$str = "1110001110000";
$arr = str_split($str);
$nf = new NumberFormatter("en", NumberFormatter::SPELLOUT);
Foreach($arr as $numb){
echo $nf->format($numb) . " ";
}
Output:
one one one zero zero zero one one one zero zero zero zero
https://3v4l.org/nHX59