Search in a multidimensional array and get the key?

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
Th3D3V1L
New php-forum User
New php-forum User
Posts: 2
Joined: Sat Apr 27, 2019 4:25 am

Sat Apr 27, 2019 4:41 am

Hello everyone, I was wondering if someone could explain to me how I could search in a multidimensional array and get the key?

Here is the example array:

Code: Select all

$data = array(
  0 => array(
    'name' => 'name one',
    'lastname' => 'last name one',
    info => array(
      'tag' => 'some tag',
      'itemId' => 'item id one'
    )

    ),
    1 => array(
      'name' => 'name two',
      'lastname' => 'last name two',
      info => array(
        'tag' => 'some tag',
        'itemId' => 'item id two'
      )
  
    )
      );
I want to search for "item id two" and get the array key of 1, or if I searched for "item id one" then I get the key 0.
Sorry for my bad English, I hope someone will help me.

User avatar
hyper
php-forum Fan User
php-forum Fan User
Posts: 831
Joined: Mon Feb 22, 2016 5:52 pm

Sat Apr 27, 2019 11:17 am

You'll need to iterate through the arrays.

Th3D3V1L
New php-forum User
New php-forum User
Posts: 2
Joined: Sat Apr 27, 2019 4:25 am

Sun Apr 28, 2019 6:12 am

I was able to solve this, here is my solution:

Code: Select all

     $i = 0;
     foreach ($data as $datas) {
       $i++;
       if ($datas['info']['itemId'] == 'item id one' ){
         echo "success $i";
         break;
       }
     } 

Post Reply