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,926 questions

51,859 answers

573 users

How to add leading zeros to the shorter string of two strings in PHP

1 Answer

0 votes
function addLeadingZero($str1, $str2) {
    $len1 = strlen($str1);
    $len2 = strlen($str2);

    $strToPad = "";

    $diff = abs($len1 - $len2);

    if ($diff > 0) {
        $strToPad = str_pad($strToPad, $diff, '0', STR_PAD_LEFT);
        if ($len1 > $len2) {
            $strToPad .= $str2;
        } else {
            $strToPad .= $str1;
        }
    }

    return $strToPad;
}

$str1 = "123";
$str2 = "8976753";

if (strlen($str1) > strlen($str2)) {
    $str2 = addLeadingZero($str1, $str2);
} else {
    $str1 = addLeadingZero($str1, $str2);
}

echo $str1 . "\n";
echo $str2 . "\n";



/*
run:

0000123
8976753

*/

 



answered May 26, 2024 by avibootz

Related questions

...