0

how to get index of repeated data from a multi dimension array using array_search() or array_column() method

function Search($value, $array) 
{ 
return(array_search($value, $array,false)); 
}
$array = array(45, 5, 1, 22, 22, 10, 10); 
$value = "10"; 
$index1= Search($value, $array);
echo $index1;

this displays index of first '10' from array. How do I get index of 2nd 10 from the array in $index2 varaible. Please help this will help me a lot.

  • 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. [doc](https://www.php.net/manual/en/function.array-search.php) – jibsteroos Jul 03 '19 at 07:40

2 Answers2

2

It is described in array_search manual:

function Search($value, $array) 
{ 
    return array_keys($array, $value, false); 
}

$array = array(45, 5, 1, 22, 22, 10, 10); 
$value = "10"; 
$indexes = Search($value, $array);
print_r($indexes);

You can see full documentation of array_keys here

dWinder
  • 11,597
  • 3
  • 24
  • 39
u_mulder
  • 54,101
  • 5
  • 48
  • 64
-1

Use array_count_values() and array_keys

DEMO

<?php
$array = array(45, 5, 1, 22, 22, 10, 10); 

//use array_count_values to counts all the values of an array.
$get_repeated_value = array_count_values($array);

$final_array = array();
foreach($get_repeated_value as $key => $value){

    //If value is repeated, get the index of that values from array.
    if($value > 1){
        $final_array[$key] = array_keys($array, $key); 
    }
}


echo "<pre>";
print_r($final_array);

?>
Shivendra Singh
  • 2,986
  • 1
  • 11
  • 11