Home > Back-end >  Searching string nested array - PHP
Searching string nested array - PHP

Time:04-02

I have a question regarding nested array

dd($this->forest);

it give me this:

array:2 [▼
  0 => array:3 [▼
    "id" => 12
    "location" => 'east'
    "type" => 'reservation'
  ]
  1 => array:3 [▼
    "id" => 13
    "location" => 'west'
    "type" => 'rainforest'
  ]
  2 => array:3 [▼
    "id" => 14
    "location" => 'north'
    "type" => 'rainforest'
  ]
]

so I want to search 'swamp' and 'mangrove' like "type" => 'swamp' or "type" => 'mangrove' but these type is not in the array of $this->forest. So, I have used in_array to sort it out.

$this->typeOfForest = '';

foreach($this->forest as $item){
  if(!in_array('swamp', $item)){
    $this->typeOfForest = 'swamp_not_found';
    break;
  }
  elseif(!in_array('mangrove', $item)){
    $this->typeOfForest = 'mangrove_not_found';
    break;
  }
}

dd($this->typeOfForest);

but when I dd($this->typeOfForest); it will not set as $this->typeOfForest = 'swamp_not_found'; instead $this->typeOfForest = 'mangrove_not_found';

Also, when I insert new data 'swamp' into array $this->forest; and run again in_array function it will give me $this->typeOfForest = 'swamp_not_found'; instead of $this->typeOfForest = 'mangrove_not_found';

Thank you!

CodePudding user response:

As said in the comments, the in_array function does not work with a multidimensional array. You need to use the array_column function to get all the types and then just do a lookup.

$this->typeOfForest = null;
$types = array_column($this->forest,'type');
if(in_array('swamp', $types)){
    $typeOfForest = 'swamp found';
}elseif(in_array('mangrove', $types)){
    $typeOfForest = 'mangrove found';
}
var_dump($this->typeOfForest);

CodePudding user response:

You are using in_array function, it just searches for a given value in every index of the array, But as you have a 2D array, So in_array cant find any index with value JUST 'swamp', so your first IF condition becomes TRUE. You can do like this:

$this->typeOfForest = '';
foreach($this->forest as $item){

   if ($item['type'] == 'swamp'){
      $typeOfForest='swamp found';
      break;
   }
   elseif($item['type'] == 'mangrove'){
     $typeOfForest='mangrove found';
      break;
   }
}
  var_dump($this->typeOfForest);
  • Related