Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to convert an array of digits to an integer add 1 and convert it back to an array of digits in PHP

1 Answer

0 votes
function convertArrayOfDigitsToIntNumber($arr) {
    $n = 0;
    
    foreach ($arr as $digit) {
        $n = $n * 10 + $digit;
    }
    
    return $n;
}

function convertIntNumberToArrayOfDigits(&$digits, $n) {
    $i = count($digits) - 1;
    
    while ($n > 0) {
        $digits[$i] = $n % 10;
        $n = (int)($n / 10);
        $i--;
    }
}

$arr = [9, 4, 6, 9];

$n = convertArrayOfDigitsToIntNumber($arr);
$n++;

convertIntNumberToArrayOfDigits($arr, $n);

echo "n = " . $n . "\n";
echo "[" . implode(", ", $arr) . "]\n";



/*
run:

n = 9470
[9, 4, 7, 0]

*/

 



answered May 6, 2024 by avibootz
...