-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

3
  • 1
    do you mean array_unique? Commented Jul 12, 2013 at 9:50
  • 4
    My advice: go read the manual, read a good book and practice. For the sake of not leaving my comment "empty": echo implode(array_unique($letters)); Commented Jul 12, 2013 at 9:52
  • 2
    stackoverflow.com/questions/307650/… Commented Jul 12, 2013 at 9:55

3 Answers 3

2

You could strip non-unique elements first:

foreach(array_unique($letters) AS $char)
Sign up to request clarification or add additional context in comments.

1 Comment

I see no sense in using loop for it.
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

Comments

0

Try like

<?php

$letters = array("A","B","B","C");
  $letters = array_unique($letters);
  foreach ($letters as $char){        
       echo $char;
  }
?>

2 Comments

Also, array_unique($letters) should be $letters = array_unique($letters); $letters isn't being passed by reference as with sort($letters). php.net/manual/en/function.array-unique.php
Sorry its just an typo...forgotted to put assigning

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.