-3

Is there any way of not copying the specific array in the foreach loop? Here's the code

<?php

    $letters = array("A","B","B","C");

      foreach ($letters as $char){
        if ($char == "B") {
          continue; 
        }
        echo $char;
      }

?>

I want my output to be only ABC not AC

Mr.Nivek
  • 55
  • 1
  • 8

3 Answers3

2

You could strip non-unique elements first:

foreach(array_unique($letters) AS $char)
Adam Hopkinson
  • 28,281
  • 7
  • 65
  • 99
0

Try like

<?php

$letters = array("A","B","B","C");
  $letters = array_unique($letters);
  foreach ($letters as $char){        
       echo $char;
  }
?>
GautamD31
  • 28,552
  • 10
  • 64
  • 85
  • Also, `array_unique($letters)` should be `$letters = array_unique($letters);` `$letters` *isn't* being passed by reference as with `sort($letters)`. http://php.net/manual/en/function.array-unique.php – PleaseStand Jul 12 '13 at 09:53
  • Sorry its just an typo...forgotted to put assigning – GautamD31 Jul 12 '13 at 09:53
0

To copy array use

$a = array("A","B","B","C");
$b = array_unique($a); // $b will be a different array with unique values

There is no need to use foreach. In PHP by default variables are not assigned by reference but by the value unless you use & operator.

The other way is to use array_merge()

$a = array("A","B","B","C");
$b = array();
$b = array_merge(array_unique($a), $b);

In both cases the result will be A B C

Robert
  • 19,800
  • 5
  • 55
  • 85