user1032531 user1032531 - 2 months ago 16
PHP Question

Searching array on multiple indexes

Given either of the following arrays (they are derived from JSON, and either can be created using

json_decode()
), how can I find the first key of the parent array for a given
x
and
y
value without manually iterating over the array? For instance, given x=1 and y=3, return 1. Ultimately, I wish to delete it, but finding it is the first step.

Array
(
[0] => Array
(
[x] => 1
[y] => 2
)

[1] => Array
(
[x] => 1
[y] => 3
)

[2] => Array
(
[x] => 2
[y] => 2
)

[3] => Array
(
[x] => 4
[y] => 2
)

[4] => Array
(
[x] => 1
[y] => 4
)

)


.

Array
(
[0] => stdClass Object
(
[x] => 1
[y] => 2
)

[1] => stdClass Object
(
[x] => 1
[y] => 3
)

[2] => stdClass Object
(
[x] => 2
[y] => 2
)

[3] => stdClass Object
(
[x] => 4
[y] => 2
)

[4] => stdClass Object
(
[x] => 1
[y] => 4
)

)

Answer

array_search will do exactly that according to the documentation:

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

$data = [["x" => 1, "y" => 2], 
         ["x" => 1, "y" => 3], 
         ["x" => 2, "y" => 2],
         ["x" => 4, "y" => 2]];
$result = array_search(["x" => 2, "y" => 2], $data);
echo $result;

Output:

2
Comments