Hi all, I have a small task that has to be solved:
I have an array:

$array = array(
"123", "1a23a", "1b23b"
);

What I want is, to delete all the "2"-s in all of its ellements and finnaly to get:

$array2 = array(
"13", "1a3a", "1b3b"
);

I tried this code:

$array = array(
"123", "1a23a", "1b23b"
);
foreach($array as $val) {
str_replace("2", "", $val);
}

...but nothing happaned. Do you have any ideas?

    The reason why nothing seemed to happen is that $val is created with a copy of the data from the array - not a reference to the array item itself. Adding an '&' (ampersand) in front of the $val variable in the foreach() statement would make this variable a reference instead, thus achieving the desired result of modifying the array value itself when you modify the dummy variable $val.

    EDIT: Forgot to note that the foreach() loop itself is unnecessary; you can simply pass [man]str_replace/man an array and it will know to walk through the array, e.g.

    $array = str_replace('2', '', $array);

    If you're only filtering out a single character (or a simple string of characters), then I think str_replace() would be a more efficient solution that using a preg_*() alternative.

      pastet89;10899557 wrote:

      Hi all, I have a small task that has to be solved:
      I tried this code:

      $array = array(
      "123", "1a23a", "1b23b"
      );
      foreach($array as $val) {
      str_replace("2", "", $val);
      }

      ...but nothing happaned. Do you have any ideas?

      Pastet89, you were so close 🙂
      try:

      $array = array(
      "123", "1a23a", "1b23b"
      );
      foreach($array as &$val) {
      $val = str_replace("2", "", $val);
      }
      echo '<pre>'.print_r($array, true);
      
      

      Output:

      Array
      (
          [0] => 13
          [1] => 1a3a
          [2] => 1b3b
      )
      

      Two things went wrong in your initial code..
      a) you did not assign anything to be equal to str_replace... so in this case, reassign $val towhat str_replace will give you...
      b) If you want to manipulate the direct array keys' values, you use an ampersand (&) infront of the value (passing a value by reference), otherwise, you are manipulating a copy of the array's values, meaning that once you are finished with foreach, the orginal array's values are untouched.

      @wtg21.org, it is not neceesary to preg here.. see this thread.

        bradgrafelman wrote:

        ...when you modify the dummy variable $val.

        ...which in the original code doesn't happen either.

          True - I must have glossed over the missing '$val =' as soon as I noticed that he was doing a PBV instead of PBR. :o

            foreach($array as &$val){
            $arr1[] = str_replace("2", "", $val);
            }
            print_r($arr1);

              ranjita: That won't replace any array values, it will store the values in new elements, doubling the size of the array.

                Or of course you could use one of the many php functions to do it for you: [man]array_walk[/man].

                $array = array("123", "1a23a", "1b23b");
                
                array_walk($array, create_function('&$v, $key', '$v = str_replace(\'2\', '', $v);'));

                It's a bit awkward with that syntax... but you could reuse the function if you needed to elsewhere... rather than having 30 "foreach" items in your code. It's just another option to do the same thing.

                  IMO, Brad's post about

                  $array = str_replace('2', '', $array);
                  

                  is about as simplistic as it gets.

                    bradgrafelman;10899712 wrote:

                    ranjita: That won't replace any array values, it will store the values in new elements, doubling the size of the array.

                    function test(&$item, $key){
                    $item = str_replace("2", "", $item);
                    }
                    $array = array("123", "1a23a", "1b23b");

                    	array_walk($array, 'test');
                        print_r($array);

                    Hope this works

                      ranjita: yes, it will work, since it's pretty-much what I posted above....

                      nrg_alpha: While I agree, Brad's is the simplest, sometimes just replacing one or two letters isn't what you want. Then it's a question of whether to do "foreach" or "array_walk". Depends on what you want to do. Just a matter of taste and what you're doing.

                        bpat1434;10899788 wrote:

                        nrg_alpha: While I agree, Brad's is the simplest, sometimes just replacing one or two letters isn't what you want. Then it's a question of whether to do "foreach" or "array_walk". Depends on what you want to do. Just a matter of taste and what you're doing.

                        I was referring to this particular OP's case..(which in this case is replacing just a single character), thus Brad's solution (as it turns out) was the simplest.

                        EDIT - In a timed test (admittedly, I had to use a loop of say 1000 times to exagerate the differences, in the case of simply replacing a character, Brad's solution clocked in the fastest, with foreach and passing value by reference came in second, and array_walk last...) But the speed differences in a single pass would be so small, it wouldn't really matter....

                        @, the $key in your function is not needed.

                          bpat1434 wrote:

                          Then it's a question of whether to do "foreach" or "array_walk".

                          Personally I'd prefer "array_map", but that may just be my functional programming bent.

                            nrg_alpha wrote:

                            admittedly, I had to use a loop of say 1000 times to exagerate the differences

                            'Exagerate[sic]'? Hardly! For the scale that we're talking about, I would think that 1000 repetitions is on the very very low end (perhaps too low, even?). That number could be multipled at least by a factor of 10 to approach 'sufficiently thorough' I would think.

                            But as bpat suggested, sometimes a particular problem can complicate itself later on down the road and you may need more functionality to solve it. I simply took the OP's present situation and developed the simplest solution for it. If you used a more thorough approach now then it may be marginally easier to adapt the code later if you have more complicated search/replace requirements.

                              Write a Reply...