0

I have a variable with some various phrases/words in there, these are all separated by a comma. They are currently in the correct order within this variable.

However when I use

<?php 
  explode(",", $variable)
?>

The result when I loop through this array one by one and print out these words into a list is that they are in alphabetical order.

So my question is how do I retain this order.

The loop is as follows

 <?php
    if(!empty($variable)) {
      print '<ul>';
      foreach($variable as $key=>$value) {
        print '<li>- '.$value.' ' . '</li>';
      }
      print '</ul>';
    }
 ?>
  • 1
    Don't describe your code, post it! – georg Nov 20 '14 at 08:56
  • 1
    `explode(',', $variable)` is the proper syntax... Please supply us with the complete source and an example string – RichardBernards Nov 20 '14 at 08:56
  • 1
    explode will not sort an array. We need to see the full code to find out what's going wrong. – t.h3ads Nov 20 '14 at 08:57
  • Where is your *assignment*? From what you wrote it seems you might think that explode directly changes the given string. This is not the case, you'll need to assign or use the return value. `$variable` will not be changed. – Yoshi Nov 20 '14 at 09:14
  • This was an issue with the loop as I tried it with a for loop and the order was retained. Can anyone explain why this is happening? – Joe northern Nov 20 '14 at 16:22

2 Answers2

0

explode doesn't change the order of the string elements check the result of this

<?php

$arr = explode(",", $variable);
foreach($arr as $element) {
    echo $element;
}
RichardBernards
  • 3,146
  • 1
  • 22
  • 30
Att3t
  • 466
  • 2
  • 8
0

Explode doesnot change the order of the splitted words.

This if you explode the string stack overflow user by space,

the array will have:

stack
overflow
user

So, no need to think upon it.

$arr = explode(",", $variable);
echo '<pre>';
print_r($arr);
echo '</pre>';

Will simply work.

Pupil
  • 23,834
  • 6
  • 44
  • 66