-1

I have an array of array like this

$data=array(
      array("9900","1","7"),
      array("9901","1","7"),
      array("9902","1","7"),
      array("9903","1","4"),
      array("9904","3","8"),
      array("9908","1","5")
);

I have value 9908. When I search 9908 then the value array("9908","1","5") should be printed. I have used array_search() but I have not got any success

How I can print the array after finding the value

Rohitashv Singhal
  • 4,517
  • 13
  • 57
  • 105
  • 2
    This is a duplicate. Please search SO before posting. – mickmackusa Oct 19 '17 at 05:38
  • https://stackoverflow.com/questions/6661530/php-multidimensional-array-search-by-value this gets you the key to access the subarray – mickmackusa Oct 19 '17 at 05:42
  • Your duplicate question is not crystal clear. Are you only searching the first column values? Will there be only one match or might there be multiple matches in the search results? Knowing exactly what you are asking is important while searching for the best possible link to close this unresearched duplicate question with. – mickmackusa Oct 19 '17 at 05:54

4 Answers4

2

Try this:

var_dump($data[array_search("9908", array_column($data, 0))]);

To expand it,

array_column returns the values from a single column of the input, identified by the column_key. Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array.


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

Edit:

To add some control over it:

$index = array_search("9908", array_column($data, 0));
if($index !== false){
    // do your stuff with $data[$index];
    var_dump($data[$index]);
}

Dumps:

array(3) {
  [0]=>
  string(4) "9908"
  [1]=>
  string(1) "1"
  [2]=>
  string(1) "5"
}
Taha Paksu
  • 15,371
  • 2
  • 44
  • 78
1

Perhaps this can help:

<?php
function search_first_row($needle, $haystack){
  $data = $haystack;
  $desired_value = $needle;
  foreach($data as $row){
    if($row[0] == $desired_value){
        return $row;
    }
  }
}
Felipe Valdes
  • 1,998
  • 15
  • 26
0
 $data=array(
    array("9900","1","7"),
    array("9901","1","7"),
    array("9902","1","7"),
    array("9903","1","4"),
    array("9904","3","8"),
    array("9908","1","5")
);
$searchValue = '9908';

for($i=0; $i<count($data); $i++){
    $innerArray = $data[$i];

    for($j=0; $j<count($innerArray); $j++){
        if($innerArray[$j] == $searchValue){
            print_r($innerArray);
        }
    }
}
Haziq Ahmed
  • 87
  • 1
  • 6
0

try this :

    $data=array(
      array("9900","1","7"),
      array("9901","1","7"),
      array("9902","1","7"),
      array("9903","1","4"),
      array("9904","3","8"),
      array("9908","1","5")
);
foreach ($data as $key => $value) {

    if( in_array("9908",$value)){
        $findindex = $key;
}
}
var_dump($data[$findindex]);
スージン
  • 143
  • 8