-2

I have an array which looks like this:

$a = [
  0 => "0",
  1 => "01",
  2 => "00",
]

I want to replace single zeros with two zeros.

should look like this:

[
  0 => "00",
  1 => "01",
  2 => "00",
]

I did this:

$newDigit = str_replace("0", "00", $splitDigit);

But it added everywhere 2 zeros:

[
  0 => "000",
  1 => "0001",
  2 => "0000",
]

How do I solve this?

Maksym Semenykhin
  • 1,924
  • 15
  • 26
utdev
  • 3,942
  • 8
  • 40
  • 70

4 Answers4

2
foreach($arr as $str)
    $str = preg_replace('/^(0)$/', '00', $str);

or

foreach($arr as $str)
    if($str === '0')
            $str = '00';

or

sprintf() that is told.

Mahdyfo
  • 1,155
  • 7
  • 18
0

sprintf() is your friend:

$array = ["0", "01", "02"];

function doubleO($v){
    return(sprintf("%02d",$v));
}

$array = array_map("doubleO",$array);
print_r($array);

Outputs:

Array ( [0] => 00 [1] => 01 [2] => 02 )

Ben
  • 8,894
  • 7
  • 44
  • 80
  • I'm not the op, but if I copy paste your code, I get `Array ( [0] => d [1] => d [2] => d )` – FirstOne Jun 30 '16 at 11:01
  • @FirstOne Then you've copied it incorrectly mate... Just tested it twice because you made me paranoid and it's definitely working. [Screenshot Link](http://i.imgur.com/YvfUx1s.png) – Ben Jun 30 '16 at 11:02
0

Why not use do the replacement within a loop instead? Here:

<?php
        $arrDigits = [
                               0 => "0"
                               1 => "01"
                               2 => "00"
                              ];

        foreach($arrDigits as $key=>$strDigit){
            If ($strDigit == "0"){
                 $arrDigit[$key] = str_replace("0", "00", $strDigit);
            }
        }
        var_dump($arrDigits);
Poiz
  • 7,611
  • 2
  • 15
  • 17
0

Why not do the replacement within a simple loop, instead?

<?php
        $arrDigits = [
                               0 => "0"
                               1 => "01"
                               2 => "00"
                              ];

        foreach($arrDigits as $key=>$strDigit){
            If ($strDigit == "0"){
                 $arrDigit[$key] = str_replace("0", "00", $strDigit);
            }
        }
        var_dump($arrDigits);
Poiz
  • 7,611
  • 2
  • 15
  • 17