2

Here I am Having an Issue:

I have two arrays like the following:

  $array1 = array('1','2','1','3','1');
  $array2 = array('1','2','3'); // Unique $array1 values

with array2 values i need all keys of an array1

Expected Output Is:

 1 => 0,2,4
 2 => 1
 3 => 3

here it indicates array2 value =>array1 keys

1
  • 1
    i have tried with array_search(1, $array1) it is displaying only one matching key............. Commented May 7, 2013 at 13:26

3 Answers 3

10

Just use a loop:

$result = array();
foreach ($array1 as $index => $value) {
  $result[$value][] = $index;
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you pass array_keys a 2nd parameter, it'll give you all the keys with that value.

So, just loop through $array2 and get the keys from $array1.

$result = array();
foreach($array2 as $val){
    $result[$val] = array_keys($array1, $val);
}

Comments

1

The following code will do the job. It will create a result array in which the attribute val will contain the value that is searched in array and keys attribute will be an array that contains the found keys. Based on your values following is an example:

$array1 =array('1','2','1','3','1');
$array2 =array('1','2','3');

$results = array();

foreach ($array2 as $key2=>$val2) {
    $result = array();
    foreach ($array1 as $key1=>$val1 ) {
        if ($val2 == $val1) {
            array_push($result,$key1);  
        }
    }
    array_push($results,array("val"=>$val2,keys=>$result ));
}

 echo json_encode($results);

The result will be:

[{"val":"1","keys":[0,2,4]},
 {"val":"2","keys":[1]},
 {"val":"3","keys":[3]}]

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.