1

I'm using sort to sort an array alphabetically that's done like this:

$Consumer[] = "Norman";
$Consumer[] = "Food";
$Consumer[] = "Clothes";
$Consumer[] = "Chips";

But when I use this code to output the array, it won't work.

$cat = sort($Consumer);
foreach ($cat as $value) 
{
   echo '<option value="'.$value.'">'.$value.'</option>';
}

It works if I remove the sort. What am I doing wrong here and how do I set this right?

0

2 Answers 2

4

sort function returns boolean value so you are overwriting your data. It modifies your $Consumer variable by reference.

Try with:

sort($Consumer);
foreach ($Consumer as $value) 
{
   echo '<option value="'.$value.'">'.$value.'</option>';
}
Sign up to request clarification or add additional context in comments.

Comments

3

sort acts by reference

As indicated in the docs sort acts by reference and returns a boolean

bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

so $cat is a boolean (true or false).

The following is a working example of your code:

$Consumer[] = "Norman";
$Consumer[] = "Food";
$Consumer[] = "Clothes";
$Consumer[] = "Chips";

sort($Consumer);
foreach ($Consumer as $value) 
{
   echo '<option value="'.$value.'">'.$value.'</option>';
}

1 Comment

Actually, sort() returns a boolean.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.