1

I have a multi dimensional array like this ;

 A:    Array ( 
        [0] => Array ( [id] => 1 [name] => name1 ) 
        [1] => Array ( [id] => 2 [name] => name2 ) 
        [2] => Array ( [id] => 3 [name] => name3 ) 
        )

And I have a array like this;

 B:    Array ( 
        [0] => Array ( [id] => 2 [name] => name2 )
        )

How to get the position of $b in $a? I want an output like 0,1,2...

Else if B = name2 can I get the position from A as 0,1,2... ?

1 Answer 1

1

You can use array_search()

array_search — Searches the array for a given value and returns the first corresponding key if successful

<?php

$a= [
        ['id'   =>  1, 'name'   =>  'name1'],
        ['id'   =>  2, 'name'   =>  'name2'],
        ['id'   =>  3, 'name'   =>  'name3'],
       ];

$b= ['id'   =>  2, 'name'   =>  'name2'];

$index = array_search($b, $a);

echo $index;      

?>

Output: 1

Since your needle position is in index 1 of array $a, you will get 1.

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

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.