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

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

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

Disclosure: My content contains affiliate links.

43,227 questions

56,129 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
...