Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array by value and store in variable

$array = array(5,4,6,8,5,3,4,6,1);

I want to sort $array like asort does, but the problem is that asort is a function and its product can't be stored in a variable.

How can I do something like this?:

$array = array(5,4,6,8,5,3,4,6,1);
$sorted_array = asort($array);

Edit: I also want $array to keep its original order.

like image 742
UserIsCorrupt Avatar asked Mar 23 '13 05:03

UserIsCorrupt


People also ask

How do you store array values in a variable?

First create a number of arrays that each stores one dimensional data, then store these arrays in a new array to create the second dimension. 2. Create a two dimensional array directly and store the data in that.

Can we store array in variable?

Declaring a Variable to Refer to an Array As with declarations for variables of other types, the declaration for an array variable does not create an array and does not allocate any memory to contain array elements. The code must create the array explicitly and assign it to anArray .

How do you sort and store arrays?

The sort() method of the Arrays class works for primitive type while the sort() method of the Collections class works for objects Collections, such as LinkedList, ArrayList, etc. Let's sort an array using the sort() method of the Arrays class. In the following program, we have defined an array of type integer.

How do you sort an array by value?

PHP - Sort Functions For Arrayssort() - sort arrays in ascending order. rsort() - sort arrays in descending order. asort() - sort associative arrays in ascending order, according to the value. ksort() - sort associative arrays in ascending order, according to the key.


1 Answers

Do this for maintaining $array in its original order

$array = array(5,4,6,8,5,3,4,6,1);
$sorted_array = $array;
asort($sorted_array);

Output

http://codepad.viper-7.com/8E78Fo

like image 86
Yogesh Suthar Avatar answered Oct 19 '22 01:10

Yogesh Suthar