Valentine
Valentine

Reputation: 102

php need to sort arrays in array and get respective key

I need to sort the following multidimensional array in php and thereafter get the respective key of any array that I want:

array:3 [▼
  0 => array:1 [▼
    4 => "404"
  ]
  1 => array:1 [▼
    5 => "373"
  ]
  2 => array:1 [▼
    6 => "305"
  ]
]

In the above case, I would like to get the position / key of 5 after sorting 404, 373 and 305.

The result of this should be value 2.

Upvotes: 0

Views: 42

Answers (1)

M. Eriksson
M. Eriksson

Reputation: 13635

Just do a foreach-loop:

$array = [
  0 => [
    4 => "404"
  ],
  1 => [
    5 => "373"
  ],
  2 => [
    6 => "305"
  ]
];

foreach ($array as $index => $arr) {
    if (array_key_exists(5, $arr)) {
        echo $index + 1;
        break;
    }
}

Demo: https://3v4l.org/HH54K

Even though PHP has a bunch of built in array-functions, they can't do everything, and they are sometimes much slower than a simple foreach.

Upvotes: 2

Related Questions