tags:

views:

40

answers:

3

I have a simple array of stuff:

$array = array("apples","oranges","strawberries");

I am trying to find the order of the stuff inside the array. (sometimes the order changes, and so do the items)

I'm expecting to get something like this:

"apples" => 0, "oranges => 1, "strawberries => 2

The end result has something to do with database sorting.

Something like this, inside a foreach loop:

UPDATE tbl SET sortorder = $neworder WHERE fruit = '$fruitname'

The $neworder variable would be populated with the new order, inside the array. While the $fruit variable comes from the item inside the array.

A: 

I'm expecting to get something like this:

$array = array("apples","oranges","strawberries");
$result = array_flip($array);

huh? ;-)

zerkms
A: 

There may be a better way to do this, but this works:

$array = array("apples","oranges","strawberries");
$order = array();
foreach ($array as $index => $fruit)
{
    $order[$fruit] = $index;
}
crimson_penguin
+1  A: 

The keys are the order. This piece of code will simply flip the keys with the values to give you "apples" => 0, ..., while making sure your keys are numeric.

$order = array_flip(array_values($array));
deceze
array_values() is absolutely ambiguous here
zerkms
@zerkms What do you mean?
deceze
i mean that if you remove array_values() then the result will be the same for the situation described in question, when array is number ordered.
zerkms
@zerkms True, but what's the harm in making code more universally applicable, especially if there are no downsides (it's slower doesn't count, it's plenty fast enough)? :)
deceze
hehe :-) yep, i don't said it slow, but i prefer not to make code more complex if it's already solve tasks that it shoud solve. nothing personal to you or your answer, i just tried to make accent on this "useless" function to questioner ;-)
zerkms
@zerkms Then you probably intended to say "superfluous" instead of "ambiguous". :)
deceze
@deceze: oops %) english practice is the one of the most reason why i'm here ;-) thanks for correcting
zerkms