sumit
sumit

Reputation: 11

How to search the key of 2 dimensional array by comparing the value in php

This is my multidimensional array and i want to access the index by giving the valve like, i want the id as [0][1] if i ask the id for LIT-100

Array
(
    [0] => Array
        (
            [0] => Test-LT-100
            [1] => LIT-100
            [2] => LIT-101
            [3] => LIT-102
        )

    [1] => Array
        (
            [0] => Test-LT-101
            [1] => LIT-103
        )

    [2] => Array
        (
            [0] => Test-LIT-102
            [1] => LIT-104
            [2] => LIT-105
        )

    [4] => Array
        (
            [0] => Test-PIT-200
            [1] => PIT-200
            [2] => PIT-201
        )

    [5] => Array
        (
            [0] => Test-PI-201
            [1] => PI-203
            [2] => PI-204
        )

    [6] => Array
        (
            [0] => Test-TIT-300
            [1] => TIT-300
            [2] => TIT-301
        )

    [7] => Array
        (
            [0] => Test-CV-700
            [1] => CV-700
        )

    [8] => Array
        (
            [0] => Test-PCV-800
            [1] => PSV-800
        )

    [9] => Array
        (
            [0] => Test-TE-301
            [1] => TE-304
        )

)

Upvotes: 0

Views: 52

Answers (1)

Brigo
Brigo

Reputation: 1112

You can achieve it with a code like:

$a = [
    ["Test-LT-100", "LIT-100", "LIT-101", "LIT-102"],
    ["Test-LT-101", "LIT-103"],
    ["Test-LIT-102", "LIT-104", "LIT-105"]
];
$var = "LIT-100"; //The variable value you're searching for

foreach ($a as $key => $array) {
    $res = array_search($var, $array);
    if ($res) {
        $key_1 = $key;
        $key_2 = $res;
        break; //When the searched variable is found, it exits the foreach loop
    }
}

echo $a[$key_1][$key_2]; //Proof of work: must print out the string you searched for; in this case: LIT-100.

Upvotes: 1

Related Questions