How to get all keys of an array with the same value
I try pretty much everything, read the whole php.net and I cannot find a way to get an array of all keys having the same value.
For example, this is an array:
Array
(
[869] => 87
[938] => 89
[870] => 127
[871] => 127
[940] => 127
[942] => 123
[947] => 123
[949] => 75
)
The array we want in my case:
Array
(
[1] => array
(
[1] => 870
[2] => 871
[3] => 940
)
[2] => array
(
[1] => 942
[2] => 947
)
)
0
source to share
3 answers
Here is a function that will do what you want. Many of them may not be the simplest, but this works:
<?php
$myArray = array(
869 => 87,
938 => 89,
870 => 127,
871 => 127,
940 => 127,
942 => 123,
947 => 123,
949 => 75
);
$newArray = $foundKeys = array();
$itt = 0;
foreach($myArray as $i => $x){
foreach($myArray as $j => $y ){
if($i != $j && !in_array($i,$foundKeys) && $x == $y){
if(!is_array($newArray[$itt])){
$newArray[$itt] = array($i);
}
array_push($newArray[$itt],$j);
array_push($foundKeys,$j);
}
}
$itt++;
}
print_r($newArray);
leads to:
Array
(
[2] => Array
(
[0] => 870
[1] => 871
[2] => 940
)
[5] => Array
(
[0] => 942
[1] => 947
)
)
+1
source to share
It would be easier to do if your second array had the value you are checking, for example, as a key.
Array
(
[127] => array
(
[1] => 870
[2] => 871
[3] => 940
)
[123] => array
(
[1] => 942
[2] => 947
)
)
Then you can do something like this:
<?php
$output = array();
foreach($your_array as $key => $current) {
if( !array_key_exists($current, $output) ) {
// create new entry
$output[$current] = array( $key );
} else {
// add to existing entry
$output[$current][] = $key;
}
}
print_r($output);
?>
This should return the result above ...
+1
source to share