PHP Learner
PHP Learner

Reputation: 43

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 I'd need to find the index for "really". How can I do this?

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 :(

Upvotes: 0

Views: 66

Answers (3)

user5125586
user5125586

Reputation:

Try:

$search = 'really';

$index = -1;
$location = [];

foreach($i = 0; $i < sizeof($array); $i++){
    for($j = 0; $j < sizeof($array[$i]); $j++){
        if($search == $array[$i][$j]){
            $location = [$i, $j];
            $index++;
            break;
        } else {
            $index++;
        }
    } 
}

print_r($location); // This gives you the position where the match is found i.e. [2, 0];
echo $index; // This is the direct index of the search result i.e. 6

print($index);

This should work. Didn't get to try it, but it should...

Upvotes: 0

Dawid G&#243;ra
Dawid G&#243;ra

Reputation: 165

for ($i = 0; $i < count($array); $i++) {
    if (($key = array_search($search, $array[$i])) !== false) {
        var_dump(array($i, $key));
    }
}

Upvotes: 0

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41820

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.

Upvotes: 1

Related Questions