PHP Learner PHP Learner -4 years ago 62
PHP Question

PHP - How to search for the index of a string in a 2 dimensional array

i need to find the of index a string in the following array after it has been exploded. so in the example id need to find the index' for "really". all tips gratefully received :) thank you!

function explode2D($row_delim, $col_delim, $str) {
return array_map(function ($line) use ($col_delim) {
return explode($col_delim, $line);
}, explode($row_delim, $str));
} // - slick coding by trincot


$string = 'red<~>blue<~>orange[|]yellow<~>purple<~>green[|]really<~>dark<~>brown';

$array = explode2D("[|]", "<~>", $string);


this returns

Array
(
[0] => Array
(
[0] => red
[1] => blue
[2] => orange
)

[1] => Array
(
[0] => yellow
[1] => purple
[2] => green
)

[2] => Array
(
[0] => really
[1] => dark
[2] => brown
)

)


so i tried this

$search = 'really';

$index = array_search($search, $array);

print($index);


nothing :(

Answer Source

array_search won't work because you're looking for a string in an array of arrays. You need to loop over the outer array and array_search each set inside that array.

foreach ($array as $key => $set) {
    $index = array_search($search, $set);
    if (false !== $index) {
        echo "Found '$search' at index $index of set $key";
        break;
    }
}

I'm not sure which index you're looking for, because with a structure like this, there are two indexes that indicate where your search string is, one for the outer array and one for the inner array. But if you break the loop after $search is found, then $key will be the correct index of the outer array at that point, so you'll have both of them.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download