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.

1
  • 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 Commented Jul 3, 2019 at 7:40

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

-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);

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.