How to sort an array in php - php

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.

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

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.

Try to use this.
sort($array);

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.

Related

Counting unique occurences of country in a php array and adding them to a statistics array [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Unique entries in an array
Let assume the array is sorted, how can I get number of counts for each unique items
Example:
$array = array ("bye", "bye", "bye", "hello", "hello");
Output:
bye = 3
hello = 2
If you want to get the total count of unique values in a specified column within a given array, as a simple integer (rather than another array) try something simple like this:
$uniqueCount = count(array_unique(array_column($data, 'column_name')));
// (where $data is your original array, and column_name is the column you want to cycle through to find the total unique values in whole array.)
var_dump(array_count_values(array("bye", "bye", "bye", "hello", "hello")));
You can use array_count_values.
print_r(array_count_values($array));
will return :
Array
(
[bye] => 3
[hello] => 2
)
You can use array_count_values on your array which would return something like:
array(2){
["bye"]=> int(3)
["hello"]=> int(2)
}
Example Usage:
$unique = array_count_values($my_array);

how do you count the number of words present in the array below? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Unique entries in an array
Let assume the array is sorted, how can I get number of counts for each unique items
Example:
$array = array ("bye", "bye", "bye", "hello", "hello");
Output:
bye = 3
hello = 2
If you want to get the total count of unique values in a specified column within a given array, as a simple integer (rather than another array) try something simple like this:
$uniqueCount = count(array_unique(array_column($data, 'column_name')));
// (where $data is your original array, and column_name is the column you want to cycle through to find the total unique values in whole array.)
var_dump(array_count_values(array("bye", "bye", "bye", "hello", "hello")));
You can use array_count_values.
print_r(array_count_values($array));
will return :
Array
(
[bye] => 3
[hello] => 2
)
You can use array_count_values on your array which would return something like:
array(2){
["bye"]=> int(3)
["hello"]=> int(2)
}
Example Usage:
$unique = array_count_values($my_array);

Returning differences in array using count

Im currently having issue's with an algorithm im creating in php using 2 separate 2 dimensional arrays.
I want to Find how different 1 array is from the other and return the value.
For now my issue is that with the algorithm im using 'should' return the same value for the 2 arrays im comparing...but currently it does not.
The values in the arrays are as follows:
$array1 contains ['index','index','index','index','index']
$array2 contains ['index','java','index','none']
When i run my algorithm :
function arrayDifference($array1,$array2)
{
if (is_array($array1)&&is_array($array2)){
$result = array_diff($array1, $array2);
$value=max(count($array1),count($array2));
$result=$value-count($result);
return $result;
}
}
I get these results:
When $array1 is passed in first the result is : 2.
When $array2 is passed in first the result is : 4.
The issue is that since im using the same arrays, should the resulting difference not be the same when both are passed in irrelevant of the parameter order?
Any help would be appreciated, thanks.
Update/Note ---------------------------------------
After printing out array_diff the first values returned from $array1 being passed in first is :
'( [1] => java [3] => none )'
and for array2 passed in first:
'Array ( ) 1'
See how array_diff() works.
In 1st case of $array1(first array in array_diff), there is only "index" value which is present in $array2 and therefore count(array_diff) is 0.
In 2nd case of $array2(first array in array_diff), there are 2 values (index,java) which are not present in $array1 therefore count(array_diff) is 2.
Thats why in first case, you get 5-0 = 5
Thats why in second case, you get 5-2 = 3

array_rand not working as expected in PHP

I was playing around with PHP as I've just begun my training in it. I came across the array_rand function that returns random indexes and you can control how many random indexes you want. But what if the number of random indexes is kept equal to the actual length of the array? I tried it and the result was surprising.
<?php
$arr = array(1,2,3,4,5,6);
$temp = array_rand($arr,6);
foreach($temp as $r){
echo $arr[$r]." ";
}
?>
So, I'm randomizing all the indices and printing the same array once again, but in the order that array_rand returns. Please note that I'm not looking for an alternative for this piece of code as I was solely practicing. What I want to know is why the random function returns Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 ) [if you print the array_rand result]? Why is it not random in this case?
array_rand is to pick some random indexes from a given array. For example it may gives you 1,3,4 indexes or 3,5,6 indexes. But not 5,2,4 (At least the purpose of the function is not that).
If you want to randomize indexes for an array you have to use shuffle
http://php.net/manual/en/function.shuffle.php
Just add one more step after arry_rand, shuffle(); so your code will be:
<?php
$arr = array(1,2,3,4,5,6);
$temp = array_rand($arr,6);
shuffle($temp);
foreach($temp as $r){
echo $arr[$r]." ";
}
?>
because as pre. answer explained the mean.

Looking up keys for a multi-dimensional array

I have an array with a key and 3 values (day, start_time, end_time). I want to keep adding certain entries into this array while making sure each entry is unique. That means that every time I try to add an item into the array, I want to make sure it does not already exist in it. If it does exist, I want to be able to find the key that indicates that entry.
For example, this is the pre-existing array:
$array [0][0] = Monday
$array [0][1] = 2
$array [0][2] = 4
$array [1][0] = Tuesday
$array [1][1] = 3
$array [1][2] = 5
If I try to insert (Wednesday, 3, 5), then it should make the entry in the index 2.
If I try to insert (Monday, 2, 4), I need to be able to know that it is already in there and is indexed by 0.
How do I go about doing this?
I agree with the other answers here — it might be better to restructure your array so that there is no need to worry about duplication at all.
If you want to keep your current structure, however: use array_search.
$array = ...
$unique_check = array_search(array('Monday', 2, 4), $array);
if ( $unique_check === false )
// add to array
else
// $unique_check = the array key at which the existing matching element is located
Why not organize the array this way?
$array [Monday][0] = 2
$array [Monday][1] = 4
$array [Tuesday][0] = 3
$array [Tuesday][1] = 5

Categories