Search an array and create an array from the results - php

I have an associated array in php of subjects with either 1 or 0 as the second value.
e.g: ([maths] => 1, [science] => 0, [english] => 1)
How can i create a new array of items that have a value of 1? i.e. (maths, english)
Thanks

$output = array_filter($input, function($v) {
return $v == 1;
});
This should do the trick (but requires PHP 5.3) - see array_filter().

$results = array();
foreach($array as $k=>$v){
if($v == 1){
$results[] = $k;
}
}

If you can guarantee that values will only ever be 1 or 0, then you can do an array_diff() to pick up every value that isn't 0.
$array = array( 'maths' => 1,
'science' => 0,
'english' => 1);
$newArray = array_diff($array, array(0));
var_dump($newArray);
EDIT
or the corresponding array_intersect() method to match every value that is a 1:
$newArray2 = array_intersect($array, array(1));
var_dump($newArray2);
If you want the original keys to become the values in your new array, then just wrap the expression in an array_keys() function. e.g.
$newArray2 = array_keys(array_intersect($array, array(1)));

$array2 = array()
foreach ( $array as $key=>$val ){
if($val == 1)
{
$array2[] = $key;
}
}

Related

Fetch row, explode and delete duplicates - PHP [duplicate]

How can I remove duplicate values from an array in PHP?
Use array_unique().
Example:
$array = array(1, 2, 2, 3);
$array = array_unique($array); // Array is now (1, 2, 3)
Use array_values(array_unique($array));
array_unique: for unique array
array_values: for reindexing
//Find duplicates
$arr = array(
'unique',
'duplicate',
'distinct',
'justone',
'three3',
'duplicate',
'three3',
'three3',
'onlyone'
);
$unique = array_unique($arr);
$dupes = array_diff_key( $arr, $unique );
// array( 5=>'duplicate', 6=>'three3' 7=>'three3' )
// count duplicates
array_count_values($dupes); // array( 'duplicate'=>1, 'three3'=>2 )
$result = array();
foreach ($array as $key => $value){
if(!in_array($value, $result))
$result[$key]=$value;
}
The only thing which worked for me is:
$array = array_unique($array, SORT_REGULAR);
Edit : SORT_REGULAR keeps the same order of the original array.
sometimes array_unique() is not the way,
if you want get unique AND duplicated items...
$unique=array("","A1","","A2","","A1","");
$duplicated=array();
foreach($unique as $k=>$v) {
if( ($kt=array_search($v,$unique))!==false and $k!=$kt )
{ unset($unique[$kt]); $duplicated[]=$v; }
}
sort($unique); // optional
sort($duplicated); // optional
results on
array ( 0 => '', 1 => 'A1', 2 => 'A2', ) /* $unique */
array ( 0 => '', 1 => '', 2 => '', 3 => 'A1', ) /* $duplicated */
We can easily use arrar_unique($array); to remove duplicate elements
But the problem in this method is that the index of the elements are not in order, will cause problems if used somewhere else later.
Use
$arr = array_unique($arr);
$arr = array_values($arr);
print_r($arr);
Or
$arr = array_flip($arr);
$arr = array_flip($arr);
$arr = array_values($arr);
print_r($arr);
The first flip , flips the key value pair thus combines the elements with similar key(that was originally the value).
2nd flip to revert all the key value pairs. Finally array_value() sets each value with key starting from 0.
Note: Not to be used in associative array with predefined key value pairs
$a = array(1, 2, 3, 4);
$b = array(1, 6, 5, 2, 9);
$c = array_merge($a, $b);
$unique = array_keys(array_flip($c));
print_r($unique);
We can create such type of array to use this last value will be updated into column or key value and we will get unique value from the array...
$array = array (1,3,4,2,1,7,4,9,7,5,9);
$data=array();
foreach($array as $value ){
$data[$value]= $value;
}
array_keys($data);
OR
array_values($data);
explode(",", implode(",", array_unique(explode(",", $YOUR_ARRAY))));
This will take care of key associations and serialize the keys for the resulting new array :-)
Depending on the size of your array, I have found
$array = array_values( array_flip( array_flip( $array ) ) );
can be faster than array_unique.
There can be multiple ways to do these, which are as follows
//first method
$filter = array_map("unserialize", array_unique(array_map("serialize", $arr)));
//second method
$array = array_unique($arr, SORT_REGULAR);
If you concern in performance and have simple array, use:
array_keys(array_flip($array));
It's many times faster than array_unique.
This example is just an alternative.
<?php
$numbers = [1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7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1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1];
$unique_numbers = [];
foreach($numbers as $number)
{
if(!in_array($number,$unique_numbers)){
$unique_numbers[] = $number;
}
}
print(json_encode($unique_numbers)); //// Array is now 1,3,4,5,6,2,7, ....
That's a great way to do it. Might want to make sure its output is back an array again. Now you're only showing the last unique value.
Try this:
$arrDuplicate = array ("","",1,3,"",5);
foreach (array_unique($arrDuplicate) as $v){
if($v != "") { $arrRemoved[] = $v; }
}
print_r ($arrRemoved);
if (#!in_array($classified->category,$arr)){
$arr[] = $classified->category;
?>
<?php } endwhile; wp_reset_query(); ?>
first time check value in array and found same value ignore it
Remove duplicate values from an associative array in PHP.
$arrDup = Array ('0' => 'aaa-aaa' , 'SKU' => 'aaa-aaa' , '1' => '12/1/1' , 'date' => '12/1/1' , '2' => '1.15' , 'cost' => '1.15' );
foreach($arrDup as $k => $v){
if(!( isset ($hold[$v])))
$hold[$v]=1;
else
unset($arrDup[$k]);
}
Array ( [0] => aaa-aaa [1] => 12/1/1 [2] => 1.15 )
$arrDuplicate = array ("","",1,3,"",5);
foreach(array_unique($arrDuplicate) as $v){
if($v != "" ){$arrRemoved = $v; }}
print_r($arrRemoved);
try this short & sweet code -
$array = array (1,4,2,1,7,4,9,7,5,9);
$unique = array();
foreach($array as $v){
isset($k[$v]) || ($k[$v]=1) && $unique[] = $v;
}
var_dump($unique);
Output -
array(6) {
[0]=>
int(1)
[1]=>
int(4)
[2]=>
int(2)
[3]=>
int(7)
[4]=>
int(9)
[5]=>
int(5)
}
<?php
$arr1 = [1,1,2,3,4,5,6,3,1,3,5,3,20];
print_r(arr_unique($arr1));
function arr_unique($arr) {
sort($arr);
$curr = $arr[0];
$uni_arr[] = $arr[0];
for($i=0; $i<count($arr);$i++){
if($curr != $arr[$i]) {
$uni_arr[] = $arr[$i];
$curr = $arr[$i];
}
}
return $uni_arr;
}
Here I've created a second empty array and used for loop with the first array which is having duplicates. It will run as many time as the count of the first array. Then compared with the position of the array with the first array and matched that it has this item already or not by using in_array. If not then it'll add that item to second array with array_push.
$a = array(1,2,3,1,3,4,5);
$count = count($a);
$b = [];
for($i=0; $i<$count; $i++){
if(!in_array($a[$i], $b)){
array_push($b, $a[$i]);
}
}
print_r ($b);
It can be done through function I made three function duplicate returns the values which are duplicate in array.
Second function single return only those values which are single mean not repeated in array and third and full function return all values but not duplicated if any value is duplicated it convert it to single;
function duplicate($arr) {
$duplicate;
$count = array_count_values($arr);
foreach($arr as $key => $value) {
if ($count[$value] > 1) {
$duplicate[$value] = $value;
}
}
return $duplicate;
}
function single($arr) {
$single;
$count = array_count_values($arr);
foreach($arr as $key => $value) {
if ($count[$value] == 1) {
$single[$value] = $value;
}
}
return $single;
}
function full($arr, $arry) {
$full = $arr + $arry;
sort($full);
return $full;
}
An alternative for array_unique() function..
Using Brute force algorithm
//[1] This our array with duplicated items
$matches = ["jorge","melvin","chelsy","melvin","jorge","smith"];
//[2] Container for the new array without any duplicated items
$arr = [];
//[3] get the length of the duplicated array and set it to the var len to be use for for loop
$len = count($matches);
//[4] If matches array key($i) current loop Iteration is not available in
//[4] the array $arr then push the current iteration key value of the matches[$i]
//[4] to the array arr.
for($i=0;$i
if(array_search($matches[$i], $arr) === false){
array_push($arr,$matches[$i]);
}
}
//print the array $arr.
print_r($arr);
//Result: Array
(
[0] => jorge
[1] => melvin
[2] => chelsy
[3] => smith
)
<?php
$a=array("1"=>"302","2"=>"302","3"=>"276","4"=>"301","5"=>"302");
print_r(array_values(array_unique($a)));
?>//`output -> Array ( [0] => 302 [1] => 276 [2] => 301 )`
I have done this without using any function.
$arr = array("1", "2", "3", "4", "5", "4", "2", "1");
$len = count($arr);
for ($i = 0; $i < $len; $i++) {
$temp = $arr[$i];
$j = $i;
for ($k = 0; $k < $len; $k++) {
if ($k != $j) {
if ($temp == $arr[$k]) {
echo $temp."<br>";
$arr[$k]=" ";
}
}
}
}
for ($i = 0; $i < $len; $i++) {
echo $arr[$i] . " <br><br>";
}
$array = array("a" => "moon", "star", "b" => "moon", "star", "sky");
// Deleting the duplicate items
$result = array_unique($array);
print_r($result);
ref : Demo

Find all array keys that has same value

Is there a simpler way to get all array keys that has same value, when the value is unknown.
The problem with array_unique is that it returns the unique array and thus it doesn't find unique values.
That is, for example, from this array:
Array (
[a]=>1000
[b]=>1
[c]=>1000
)
I want to get this
Array (
[a]=>1000
[c]=>1000
)
Another way around this is, if I could find the lonely values, and then their keys, and then use array_diff
This is what I've got so far, looks awful:
$a = array( 'a' => 1000, 'b' => 1, 'c' => 1000 );
$b = array_flip( array_count_values( $a ) );
krsort( $b );
$final = array_keys( $a, array_shift( $b ) );
Update
Using Paulo Freites' answer as a code base, I could get it working pretty easily, maintainable and easy on eyes kind of way… by using the filtering as a static class method I can get the duplicate values from an array by just calling ClassName::get_duplicates($array_to_filter)
private static $counts = null;
private static function filter_duplicates ($value) {
return self::$counts[ $value ] > 1;
}
public static function get_duplicates ($array) {
self::$counts = array_count_values( $array );
return array_filter( $array, 'ClassName::filter_duplicates' );
}
Taking advantage of closures for a more straightforward solution:
$array = array('a' => 1000, 'b' => 1, 'c' => 1000);
$counts = array_count_values($array);
$filtered = array_filter($array, function ($value) use ($counts) {
return $counts[$value] > 1;
});
var_dump($filtered);
This gave me the following:
array(2) {
["a"]=>
int(1000)
["c"]=>
int(1000)
}
Demo: https://eval.in/67526
That's all! :)
Update: backward-compatible solution
$array = array('a' => 1000, 'b' => 1, 'c' => 1000);
$counts = array_count_values($array);
$filtered = array_filter($array, create_function('$value',
'global $counts; return $counts[$value] > 1;'));
var_dump($filtered);
Demo: https://eval.in/68255
Your implementation has a few issues.
1) If there are 2 of value 1000 and 2 of another value, the array_flip will lose one of the sets of values.
2) If there are more than two different values, the array_keys will only find the one value that occurs most.
3) If there are no duplicates, you will still bring back one of the values.
Something like this works always and will return all duplicate values:
<?php
//the array
$a = array( 'a' => 1000, 'b' => 1, 'c' => 1000 );
//count of values
$cnt = array_count_values($a);
//a new array
$newArray = array();
//loop over existing array
foreach($a as $k=>$v){
//if the count for this value is more than 1 (meaning value has a duplicate)
if($cnt[$v] > 1){
//add to the new array
$newArray[$k] = $v;
}
}
print_r($newArray);
http://codepad.viper-7.com/fal5Yz
If you want to get the duplicates in an array try this:
array_unique(array_diff_assoc($array1, array_unique($array1)))
I found this from:
http://www.php.net/manual/en/function.array-unique.php#95203
at the moment I cant figure out another solution...
// target array
$your_array = array('a'=>1000, 'b'=>1, 'c'=>1000);
// function to do all the job
function get_duplicate_elements($array) {
$res = array();
$counts = array_count_values($array);
foreach ($counts as $id=>$count) {
if ($count > 1) {
$r = array();
$keys = array_keys($array, $id);
foreach ($keys as $k) $r[$k] = $id;
$res[] = $r;
}
}
return sizeof($res) > 0 ? $res : false;
}
// test it
print_r(get_duplicate_elements($your_array));
output:
Array
(
[0] => Array
(
[a] => 1000
[c] => 1000
)
)
example #2: - when you have different values multiplied
// target array
$your_array = array('a'=>1000, 'b'=>1, 'c'=>1000, 'd'=>500, 'e'=>1);
// output
print_r(get_duplicate_elements($your_array));
output:
Array
(
[0] => Array
(
[a] => 1000
[c] => 1000
)
[1] => Array
(
[b] => 1
[e] => 1
)
)
if function result has been assigned to $res variable $res[0] gets an array of all elements from original array with first value found more than once, $res[1] gets array of elements with another duplicated-value, etc... function returns false if nothing duplicate has been found in argument-array.
Try this
$a = array( 'a' => 1, 'b' => 1000, 'c' => 1000,'d'=>'duplicate','e'=>'duplicate','f'=>'ok','g'=>'ok' );
$b = array_map("unserialize", array_unique(array_map("serialize", $a)));
$c = array_diff_key($a, $b);
$array = array("1"=>"A","2"=>"A","3"=>"A","4"=>"B","5"=>"B","6"=>"B");
$val = array_unique(array_values($array));
foreach ($val As $v){
$dat[$v] = array_keys($array,$v);
}
print_r($dat);

Search array by values and return keys

I have values passed c and 3 from $_GET variable, which I want to look up in an array as values and retrieve their keys. How can I search through the array to return accurate keys?
The code below
<?php
$array1 = array(0 => 'a', 1 => 'c', 2 => 'c');
$array2 = array(0 => '3', 1 => '2', 2 => '3');
$key1 = array_search('c', $array1);
$key2 = array_search('3', $array2);
?>
returns
$key1 = 1;
$key2 = 0;
though I am expecting
$key1 = 2;
$key2 = 2;
foreach ($array1 as $key => $value) {
if ($value == 'c' && $array2[$key] == '3') {
echo "The key you are looking for is $key";
break;
}
}
I'm pretty sure there's a saner way to do whatever you're trying to do though.
The function returned exactly as it should have. The first occurrence of value 'c' exists at index 1 in $array1 and the value '3' has its first occurrence at index 0 in $array2
This behavior is documented in the php docs on array_search and it even supplies you with an alternative if you don't like it:
If needle is found in haystack more than once, the first matching key
is returned. To return the keys for all matching values, use
array_keys() with the optional search_value parameter instead.
If you want to find the last key that has that value, you could reverse your array first.
$array1 = array(0 => 'a', 1 => 'c', 2 => 'c');
$array2 = array(0 => '3', 1 => '2', 2 => '3');
$key1 = array_search('c', $array1);
$key2 = array_search('3', $array2);
var_dump($key1,$key2); //output: int(1) int(0)
$key1 = array_search('c', array_reverse($array1, true));
$key2 = array_search('3', array_reverse($array2, true));
var_dump($key1,$key2); //output: int(2) int(2)
Perhaps something like:
<?php
// for specificly 2 arrays
function search_matching($match1, $match2, array $array1, array $array2) {
foreach($array1 as $key1 => $value1) {
// we may want to add $strict = false argument to distinguish between == and === match
// see http://php.net/manual/en/function.array-search.php
if($value1 == $match1 and isset($array2[$key1]) and $array2[$key1] == $match2) {
return $key1;
}
}
return null;
}
// unlimited
function search_matching(array($matches), array $array/*, ...*/) {
if( count($matches) != func_num_args() - 1)
throw new \Exception("Number of values to match must be the same as the number of supplied arrays");
$arrays = func_get_args();
array_shift($arrays); // remove $matches
$array = array_unshift($arrays); // array to be iterated
foreach($array as $key => $value) {
if($value == $matches[0]) {
$matches = true;
foreach($arrays as $keyA => $valueA) {
if(! isset($arrays[$key] or $valueA != $matches[$keyA+1]) {
$matches = false;
break;
}
}
if($matches)
return $key;
}
}
return null;
}
The functions are created with numerical keys in mind.
They could be made cleaner by offloading some functionality to other function, but I wanted to keep it concise and together for the sake of easily seeing how it works

Switch two items in associative array

Example:
$arr = array(
'apple' => 'sweet',
'grapefruit' => 'bitter',
'pear' => 'tasty',
'banana' => 'yellow'
);
I want to switch the positions of grapefruit and pear, so the array will become
$arr = array(
'apple' => 'sweet',
'pear' => 'tasty',
'grapefruit' => 'bitter',
'banana' => 'yellow'
)
I know the keys and values of the elements I want to switch, is there an easy way to do this? Or will it require a loop + creating a new array?
Thanks
Just a little shorter and less complicated than the solution of arcaneerudite:
<?php
if(!function_exists('array_swap_assoc')) {
function array_swap_assoc($key1, $key2, $array) {
$newArray = array ();
foreach ($array as $key => $value) {
if ($key == $key1) {
$newArray[$key2] = $array[$key2];
} elseif ($key == $key2) {
$newArray[$key1] = $array[$key1];
} else {
$newArray[$key] = $value;
}
}
return $newArray;
}
}
$array = $arrOrig = array(
'fruit' => 'pear',
'veg' => 'cucumber',
'tuber' => 'potato',
'meat' => 'ham'
);
$newArray = array_swap_assoc('veg', 'tuber', $array);
var_dump($array, $newArray);
?>
Tested and works fine
Here's my version of the swap function:
function array_swap_assoc(&$array,$k1,$k2) {
if($k1 === $k2) return; // Nothing to do
$keys = array_keys($array);
$p1 = array_search($k1, $keys);
if($p1 === FALSE) return; // Sanity check...keys must exist
$p2 = array_search($k2, $keys);
if($p2 === FALSE) return;
$keys[$p1] = $k2; // Swap the keys
$keys[$p2] = $k1;
$values = array_values($array);
// Swap the values
list($values[$p1],$values[$p2]) = array($values[$p2],$values[$p1]);
$array = array_combine($keys, $values);
}
if the array comes from the db, add a sort_order field so you can always be sure in what order the elements are in the array.
This may or may not be an option depending on your particular use-case, but if you initialize your array with null values with the appropriate keys before populating it with data, you can set the values in any order and the original key-order will be maintained. So instead of swapping elements, you can prevent the need to swap them entirely:
$arr = array('apple' => null,
'pear' => null,
'grapefruit' => null,
'banana' => null);
...
$arr['apple'] = 'sweet';
$arr['grapefruit'] = 'bitter'; // set grapefruit before setting pear
$arr['pear'] = 'tasty';
$arr['banana'] = 'yellow';
print_r($arr);
>>> Array
(
[apple] => sweet
[pear] => tasty
[grapefruit] => bitter
[banana] => yellow
)
Not entirely sure if this was mentioned, but, the reason this is tricky is because it's non-indexed.
Let's take:
$arrOrig = array(
'fruit'=>'pear',
'veg'=>'cucumber',
'tuber'=>'potato'
);
Get the keys:
$arrKeys = array_keys($arrOrig);
print_r($arrKeys);
Array(
[0]=>fruit
[1]=>veg
[2]=>tuber
)
Get the values:
$arrVals = array_values($arrOrig);
print_r($arrVals);
Array(
[0]=>pear
[1]=>cucumber
[2]=>potato
)
Now you've got 2 arrays that are numerical. Swap the indices of the ones you want to swap, then read the other array back in in the order of the modified numerical array. Let's say we want to swap 'fruit' and 'veg':
$arrKeysFlipped = array_flip($arrKeys);
print_r($arrKeysFlipped);
Array (
[fruit]=>0
[veg]=>1
[tuber]=>2
)
$indexFruit = $arrKeysFlipped['fruit'];
$indexVeg = $arrKeysFlipped['veg'];
$arrKeysFlipped['veg'] = $indexFruit;
$arrKeysFlipped['fruit'] = $indexVeg;
print_r($arrKeysFlipped);
Array (
[fruit]=>1
[veg]=>0
[tuber]=>2
)
Now, you can swap back the array:
$arrKeys = array_flip($arrKeysFlipped);
print_r($arrKeys);
Array (
[0]=>veg
[1]=>fruit
[2]=>tuber
)
Now, you can build an array by going through the oringal array in the 'order' of the rearranged keys.
$arrNew = array ();
foreach($arrKeys as $index=>$key) {
$arrNew[$key] = $arrOrig[$key];
}
print_r($arrNew);
Array (
[veg]=>cucumber
[fruit]=>pear
[tuber]=>potato
)
I haven't tested this - but this is what I'd expect. Does this at least provide any kind of help? Good luck :)
You could put this into a function $arrNew = array_swap_assoc($key1,$key2,$arrOld);
<?php
if(!function_exists('array_swap_assoc')) {
function array_swap_assoc($key1='',$key2='',$arrOld=array()) {
$arrNew = array ();
if(is_array($arrOld) && count($arrOld) > 0) {
$arrKeys = array_keys($arrOld);
$arrFlip = array_flip($arrKeys);
$indexA = $arrFlip[$key1];
$indexB = $arrFlip[$key2];
$arrFlip[$key1]=$indexB;
$arrFlip[$key2]=$indexA;
$arrKeys = array_flip($arrFlip);
foreach($arrKeys as $index=>$key) {
$arrNew[$key] = $arrOld[$key];
}
} else {
$arrNew = $arrOld;
}
return $arrNew;
}
}
?>
WARNING: Please test and debug this before just using it - no testing has been done at all.
There is no easy way, just a loop or a new array definition.
Classical associative array doesn't define or guarantee sequence of elements in any way. There is plain array/vector for that. If you use associative array you are assumed to need random access but not sequential. For me you are using assoc array for task it is not made for.
yeah I agree with Lex, if you are using an associative array to hold data, why not using your logic handle how they are accessed instead of depending on how they are arranged in the array.
If you really wanted to make sure they were in a correct order, trying creating fruit objects and then put them in a normal array.
There is no easy way to do this. This sounds like a slight design-logic error on your part which has lead you to try to do this when there is a better way to do whatever it is you are wanting to do. Can you tell us why you want to do this?
You say that I know the keys and values of the elements I want to switch which makes me think that what you really want is a sorting function since you can easily access the proper elements anytime you want as they are.
$value = $array[$key];
If that is the case then I would use sort(), ksort() or one of the many other sorting functions to get the array how you want. You can even use usort() to Sort an array by values using a user-defined comparison function.
Other than that you can use array_replace() if you ever need to swap values or keys.
Here are two solutions. The first is longer, but doesn't create a temporary array, so it saves memory. The second probably runs faster, but uses more memory:
function swap1(array &$a, $key1, $key2)
{
if (!array_key_exists($key1, $a) || !array_key_exists($key2, $a) || $key1 == $key2) return false;
$after = array();
while (list($key, $val) = each($a))
{
if ($key1 == $key)
{
break;
}
else if ($key2 == $key)
{
$tmp = $key1;
$key1 = $key2;
$key2 = $tmp;
break;
}
}
$val1 = $a[$key1];
$val2 = $a[$key2];
while (list($key, $val) = each($a))
{
if ($key == $key2)
$after[$key1] = $val1;
else
$after[$key] = $val;
unset($a[$key]);
}
unset($a[$key1]);
$a[$key2] = $val2;
while (list($key, $val) = each($after))
{
$a[$key] = $val;
unset($after[$key]);
}
return true;
}
function swap2(array &$a, $key1, $key2)
{
if (!array_key_exists($key1, $a) || !array_key_exists($key2, $a) || $key1 == $key2) return false;
$swapped = array();
foreach ($a as $key => $val)
{
if ($key == $key1)
$swapped[$key2] = $a[$key2];
else if ($key == $key2)
$swapped[$key1] = $a[$key1];
else
$swapped[$key] = $val;
}
$a = $swapped;
return true;
}
fwiw here is a function to swap two adjacent items to implement moveUp() or moveDown() in an associative array without foreach()
/**
* #param array $array to modify
* #param string $key key to move
* #param int $direction +1 for down | -1 for up
* #return $array
*/
protected function moveInArray($array, $key, $direction = 1)
{
if (empty($array)) {
return $array;
}
$keys = array_keys($array);
$index = array_search($key, $keys);
if ($index === false) {
return $array; // not found
}
if ($direction < 0) {
$index--;
}
if ($index < 0 || $index >= count($array) - 1) {
return $array; // at the edge: cannot move
}
$a = $keys[$index];
$b = $keys[$index + 1];
$result = array_slice($array, 0, $index, true);
$result[$b] = $array[$b];
$result[$a] = $array[$a];
return array_merge($result, array_slice($array, $index + 2, null, true));
}
There is an easy way:
$sourceArray = array(
'apple' => 'sweet',
'grapefruit' => 'bitter',
'pear' => 'tasty',
'banana' => 'yellow'
);
// set new order
$orderArray = array(
'apple' => '', //this values would be replaced
'pear' => '',
'grapefruit' => '',
//it is not necessary to touch all elemets that will remains the same
);
$result = array_replace($orderArray, $sourceArray);
print_r($result);
and you get:
$result = array(
'apple' => 'sweet',
'pear' => 'tasty',
'grapefruit' => 'bitter',
'banana' => 'yellow'
)
function arr_swap_keys(array &$arr, $key1, $key2, $f_swap_vals=false) {
// if f_swap_vals is false, then
// swap only the keys, keeping the original values in their original place
// ( i.e. do not preserve the key value correspondence )
// i.e. if arr is (originally)
// [ 'dog' => 'alpha', 'cat' => 'beta', 'horse' => 'gamma' ]
// then calling this on arr with, e.g. key1 = 'cat', and key2 = 'horse'
// will result in arr becoming:
// [ 'dog' => 'alpha', 'horse' => 'beta', 'cat' => 'gamma' ]
//
// if f_swap_vals is true, then preserve the key value correspondence
// i.e. in the above example, arr will become:
// [ 'dog' => 'alpha', 'horse' => 'gamma', 'cat' => 'beta' ]
//
//
$arr_vals = array_values($arr); // is a (numerical) index to value mapping
$arr_keys = array_keys($arr); // is a (numerical) index to key mapping
$arr_key2idx = array_flip($arr_keys);
$idx1 = $arr_key2idx[$key1];
$idx2 = $arr_key2idx[$key2];
swap($arr_keys[$idx1], $arr_keys[$idx2]);
if ( $f_swap_vals ) {
swap($arr_vals[$idx1], $arr_vals[$idx2]);
}
$arr = array_combine($arr_keys, $arr_vals);
}
function swap(&$a, &$b) {
$t = $a;
$a = $b;
$b = $t;
}
Well it's just a key sorting problem. We can use uksort for this purpose. It needs a key comparison function and we only need to know that it should return 0 to leave keys position untouched and something other than 0 to move key up or down.
Notice that it will only work if your keys you want to swap are next to each other.
<?php
$arr = array(
'apple' => 'sweet',
'grapefruit' => 'bitter',
'pear' => 'tasty',
'banana' => 'yellow'
);
uksort(
$arr,
function ($k1, $k2) {
if ($k1 == 'grapefruit' && $k2 == 'pear') return 1;
else return 0;
}
);
var_dump($arr);
I'll share my short version too, it works with both numeric and associative arrays.
array array_swap ( array $array , mixed $key1 , mixed $key2 [, bool $preserve_keys = FALSE [, bool $strict = FALSE ]] )
Returns a new array with the two elements swapped. It preserve original keys if specified. Return FALSE if keys are not found.
function array_swap(array $array, $key1, $key2, $preserve_keys = false, $strict = false) {
$keys = array_keys($array);
if(!array_key_exists($key1, $array) || !array_key_exists($key2, $array)) return false;
if(($index1 = array_search($key1, $keys, $strict)) === false) return false;
if(($index2 = array_search($key2, $keys, $strict)) === false) return false;
if(!$preserve_keys) list($keys[$index1], $keys[$index2]) = array($key2, $key1);
list($array[$key1], $array[$key2]) = array($array[$key2], $array[$key1]);
return array_combine($keys, array_values($array));
}
For example:
$arr = array_swap($arr, 'grapefruit', 'pear');
I wrote a function with more general purpose, with this problem in mind.
array with known keys
specify order of keys in a second array ($order array keys indicate key position)
function order_array($array, $order) {
foreach (array_keys($array) as $k => $v) {
$keys[++$k] = $v;
}
for ($i = 1; $i <= count($array); $i++) {
if (isset($order[$i])) {
unset($keys[array_search($order[$i], $keys)]);
}
if ($i === count($array)) {
array_push($keys, $order[$i]);
} else {
array_splice($keys, $i-1, 0, $order[$i]);
}
}
}
foreach ($keys as $key) {
$result[$key] = $array[$key];
}
return $result;
} else {
return false;
}
}
$order = array(1 => 'item3', 2 => 'item5');
$array = array("item1" => 'val1', "item2" => 'val2', "item3" => 'val3', "item4" => 'val4', "item5" => 'val5');
print_r($array); -> Array ( [item1] => val1 [item2] => val2 [item3] => val3 [item4] => val4 [item5] => val5 )
print_r(order_array($array, $order)); -> Array ( [item3] => val3 [item5] => val5 [item1] => val1 [item2] => val2 [item4] => val4 )
I hope this is relevant / helpful for someone
Arrays in php are ordered maps.
$arr = array('apple'=>'sweet','grapefruit'=>'bitter','
pear'=>'tasty','banana'=>'yellow');
doesn't mean that that the first element is 'apple'=>'sweet' and the last - 'banana'=>'yellow' just because you put 'apple' first and 'banana' last. Actually, 'apple'=>'sweet' will be the first and
'banana'=>'yellow' will be the second because of alphabetical ascending sort order.

How to remove duplicate values from an array in PHP

How can I remove duplicate values from an array in PHP?
Use array_unique().
Example:
$array = array(1, 2, 2, 3);
$array = array_unique($array); // Array is now (1, 2, 3)
Use array_values(array_unique($array));
array_unique: for unique array
array_values: for reindexing
//Find duplicates
$arr = array(
'unique',
'duplicate',
'distinct',
'justone',
'three3',
'duplicate',
'three3',
'three3',
'onlyone'
);
$unique = array_unique($arr);
$dupes = array_diff_key( $arr, $unique );
// array( 5=>'duplicate', 6=>'three3' 7=>'three3' )
// count duplicates
array_count_values($dupes); // array( 'duplicate'=>1, 'three3'=>2 )
$result = array();
foreach ($array as $key => $value){
if(!in_array($value, $result))
$result[$key]=$value;
}
The only thing which worked for me is:
$array = array_unique($array, SORT_REGULAR);
Edit : SORT_REGULAR keeps the same order of the original array.
sometimes array_unique() is not the way,
if you want get unique AND duplicated items...
$unique=array("","A1","","A2","","A1","");
$duplicated=array();
foreach($unique as $k=>$v) {
if( ($kt=array_search($v,$unique))!==false and $k!=$kt )
{ unset($unique[$kt]); $duplicated[]=$v; }
}
sort($unique); // optional
sort($duplicated); // optional
results on
array ( 0 => '', 1 => 'A1', 2 => 'A2', ) /* $unique */
array ( 0 => '', 1 => '', 2 => '', 3 => 'A1', ) /* $duplicated */
We can easily use arrar_unique($array); to remove duplicate elements
But the problem in this method is that the index of the elements are not in order, will cause problems if used somewhere else later.
Use
$arr = array_unique($arr);
$arr = array_values($arr);
print_r($arr);
Or
$arr = array_flip($arr);
$arr = array_flip($arr);
$arr = array_values($arr);
print_r($arr);
The first flip , flips the key value pair thus combines the elements with similar key(that was originally the value).
2nd flip to revert all the key value pairs. Finally array_value() sets each value with key starting from 0.
Note: Not to be used in associative array with predefined key value pairs
$a = array(1, 2, 3, 4);
$b = array(1, 6, 5, 2, 9);
$c = array_merge($a, $b);
$unique = array_keys(array_flip($c));
print_r($unique);
We can create such type of array to use this last value will be updated into column or key value and we will get unique value from the array...
$array = array (1,3,4,2,1,7,4,9,7,5,9);
$data=array();
foreach($array as $value ){
$data[$value]= $value;
}
array_keys($data);
OR
array_values($data);
explode(",", implode(",", array_unique(explode(",", $YOUR_ARRAY))));
This will take care of key associations and serialize the keys for the resulting new array :-)
Depending on the size of your array, I have found
$array = array_values( array_flip( array_flip( $array ) ) );
can be faster than array_unique.
There can be multiple ways to do these, which are as follows
//first method
$filter = array_map("unserialize", array_unique(array_map("serialize", $arr)));
//second method
$array = array_unique($arr, SORT_REGULAR);
If you concern in performance and have simple array, use:
array_keys(array_flip($array));
It's many times faster than array_unique.
This example is just an alternative.
<?php
$numbers = [1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,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,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1,1,3,4,5,6,2,5,7,1];
$unique_numbers = [];
foreach($numbers as $number)
{
if(!in_array($number,$unique_numbers)){
$unique_numbers[] = $number;
}
}
print(json_encode($unique_numbers)); //// Array is now 1,3,4,5,6,2,7, ....
That's a great way to do it. Might want to make sure its output is back an array again. Now you're only showing the last unique value.
Try this:
$arrDuplicate = array ("","",1,3,"",5);
foreach (array_unique($arrDuplicate) as $v){
if($v != "") { $arrRemoved[] = $v; }
}
print_r ($arrRemoved);
if (#!in_array($classified->category,$arr)){
$arr[] = $classified->category;
?>
<?php } endwhile; wp_reset_query(); ?>
first time check value in array and found same value ignore it
Remove duplicate values from an associative array in PHP.
$arrDup = Array ('0' => 'aaa-aaa' , 'SKU' => 'aaa-aaa' , '1' => '12/1/1' , 'date' => '12/1/1' , '2' => '1.15' , 'cost' => '1.15' );
foreach($arrDup as $k => $v){
if(!( isset ($hold[$v])))
$hold[$v]=1;
else
unset($arrDup[$k]);
}
Array ( [0] => aaa-aaa [1] => 12/1/1 [2] => 1.15 )
$arrDuplicate = array ("","",1,3,"",5);
foreach(array_unique($arrDuplicate) as $v){
if($v != "" ){$arrRemoved = $v; }}
print_r($arrRemoved);
try this short & sweet code -
$array = array (1,4,2,1,7,4,9,7,5,9);
$unique = array();
foreach($array as $v){
isset($k[$v]) || ($k[$v]=1) && $unique[] = $v;
}
var_dump($unique);
Output -
array(6) {
[0]=>
int(1)
[1]=>
int(4)
[2]=>
int(2)
[3]=>
int(7)
[4]=>
int(9)
[5]=>
int(5)
}
<?php
$arr1 = [1,1,2,3,4,5,6,3,1,3,5,3,20];
print_r(arr_unique($arr1));
function arr_unique($arr) {
sort($arr);
$curr = $arr[0];
$uni_arr[] = $arr[0];
for($i=0; $i<count($arr);$i++){
if($curr != $arr[$i]) {
$uni_arr[] = $arr[$i];
$curr = $arr[$i];
}
}
return $uni_arr;
}
Here I've created a second empty array and used for loop with the first array which is having duplicates. It will run as many time as the count of the first array. Then compared with the position of the array with the first array and matched that it has this item already or not by using in_array. If not then it'll add that item to second array with array_push.
$a = array(1,2,3,1,3,4,5);
$count = count($a);
$b = [];
for($i=0; $i<$count; $i++){
if(!in_array($a[$i], $b)){
array_push($b, $a[$i]);
}
}
print_r ($b);
It can be done through function I made three function duplicate returns the values which are duplicate in array.
Second function single return only those values which are single mean not repeated in array and third and full function return all values but not duplicated if any value is duplicated it convert it to single;
function duplicate($arr) {
$duplicate;
$count = array_count_values($arr);
foreach($arr as $key => $value) {
if ($count[$value] > 1) {
$duplicate[$value] = $value;
}
}
return $duplicate;
}
function single($arr) {
$single;
$count = array_count_values($arr);
foreach($arr as $key => $value) {
if ($count[$value] == 1) {
$single[$value] = $value;
}
}
return $single;
}
function full($arr, $arry) {
$full = $arr + $arry;
sort($full);
return $full;
}
As an alternative of array_unique() you may use php Set class
$array = array(1, 2, 2, 3);
$array = (new \Ds\Set($array))->toArray() ; // Array is now (1, 2, 3)
An alternative for array_unique() function..
Using Brute force algorithm
//[1] This our array with duplicated items
$matches = ["jorge","melvin","chelsy","melvin","jorge","smith"];
//[2] Container for the new array without any duplicated items
$arr = [];
//[3] get the length of the duplicated array and set it to the var len to be use for for loop
$len = count($matches);
//[4] If matches array key($i) current loop Iteration is not available in
//[4] the array $arr then push the current iteration key value of the matches[$i]
//[4] to the array arr.
for($i=0;$i
if(array_search($matches[$i], $arr) === false){
array_push($arr,$matches[$i]);
}
}
//print the array $arr.
print_r($arr);
//Result: Array
(
[0] => jorge
[1] => melvin
[2] => chelsy
[3] => smith
)
<?php
$a=array("1"=>"302","2"=>"302","3"=>"276","4"=>"301","5"=>"302");
print_r(array_values(array_unique($a)));
?>//`output -> Array ( [0] => 302 [1] => 276 [2] => 301 )`
I have done this without using any function.
$arr = array("1", "2", "3", "4", "5", "4", "2", "1");
$len = count($arr);
for ($i = 0; $i < $len; $i++) {
$temp = $arr[$i];
$j = $i;
for ($k = 0; $k < $len; $k++) {
if ($k != $j) {
if ($temp == $arr[$k]) {
echo $temp."<br>";
$arr[$k]=" ";
}
}
}
}
for ($i = 0; $i < $len; $i++) {
echo $arr[$i] . " <br><br>";
}
$array = array("a" => "moon", "star", "b" => "moon", "star", "sky");
// Deleting the duplicate items
$result = array_unique($array);
print_r($result);
ref : Demo

Categories