tags:

views:

137

answers:

4

i want the same value has the same index for example

1 2 2 3 5

after sort:

array(
0=>1
1=>2
1=>2
3=>3
4=>5);

but we can not set duplicate index in the array of php.

+4  A: 

There's a sort function in php! ( I answer the topic and not the body, didn't quite follow you there, but here's how you sort in php )

Example

<?php

$fruits = array("lemon", "orange", "banana", "apple");

sort($fruits);

foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

Duplicates

In the above example duplicates will just have their own indexes so the array:

5 4 5 1 3 1 2

Will look like this

1 1 2 3 4 5 5

This might not be what you are looking for, what you want is another type of dataset than just a simple array, maybe you want a hashtable or just a linked list on each row.

If you are okay with it, you can remove the duplicates by using array_unique $newArray=array_unique($arr);

Which would lead to having an array looking like this

1 2 3 4 5
Filip Ekberg
+2  A: 

Try this:

sort($array);

Treby
+2  A: 

You're right, you can't have duplicate values at the same index in an array - each index in an array has exactly one value.

As to the title of the question, to sort an array in PHP, use sort.

If this doesn't answer what you're trying to ask, you might want to edit your question to make it a bit clearer (the body of the question doesn't seem particularly related to the question title).

Post OP's edit:

You cannot store multiple values at the same key, your output array (array(0=>1, 1=>2, 1=>2, 3=>3, 4=>5);) doesn't really make sense (the key 1 does map to the value 2) in the sorted array. Are you trying to store counts of occurrences of numbers?

e.g. given the input:

1, 2, 2, 3, 5

get the output:

array(1=>1, 2=>2, 3=>1, 5=>1); // there is 1 "1", there are 2 "2"s etc.
Dominic Rodger
Hmm he might be thinking of a hashtable..
Filip Ekberg
A: 

You are looking for array_unique:

array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )

Takes an input array and returns a new array without duplicate values.

Piskvor