Acelando
Acelando

Reputation: 29

PHP Array delete an entire array by one element value

So this is how my Array ($dataArray) looks oks like:

Array 
( 
 [0] => Array 
   ( 
   [0] => Date 
   [1] => Time 
   [2] => Duration 
   [3] => Info 
   [4] => Client
   )
 [1] => Array 
   ( 
   [0] => 2021-12-01 
   [1] => 10:45:43 
   [2] => 237 
   [3] => Some text from  
   [4] => Client 1 
   ) 
 [2] => Array 
   ( 
   [0] => 2021-12-01 
   [1] => 11:29:13 
   [2] => 77 
   [3] => Nothing important 
   [4] => Client 2 
   ) 
 [3] => Array 
   ( 
   [0] => 2021-12-01 
   [1] => 11:53:03 
   [2] => 44 
   [3] => anonymous 
   [4] => Client 1 
   )

I need to Loop trough it to search the Client Names, and if i find the matching name in the Element 4 then delete the entire Array.

$ExportKDname = "Client 1"
foreach($dataArray as $key => $sub_array) {
    if($sub_array[4] == $ExportKDname) {
        unset($dataArray[$key]);
        break; 
    }
}
  
  print_r($dataArray);

But with this code none of the arrays will be deleted. And I just can not find the right way to do it.

The Final array what I need to look like if we find the "Client 1" in the array would be like this:

Array 
( 
 [0] => Array 
   ( 
   [0] => Date 
   [1] => Time 
   [2] => Duration 
   [3] => Info 
   [4] => Client
   )
 [1] => Array 
   ( 
   [0] => 2021-12-01 
   [1] => 11:29:13 
   [2] => 77 
   [3] => Nothing important 
   [4] => Client 2 
   ) 

Upvotes: 0

Views: 89

Answers (2)

Jax-p
Jax-p

Reputation: 8531

You can array_filter your variable and check if value is in_array.

With PHP 7.4+ syntax it should look like this:

$result = array_filter($dataArray, fn ($innerArray) => !in_array('Client 1', $innerArray));

Upvotes: 1

huzeyfetas
huzeyfetas

Reputation: 86

In the if condition you are saying "if u match with $sub_arr[4] == $ExportKDname unset it and stop the loop". the machine doing that. when it matched first time it removes and stoping. If u wanna delete all match do not write break; let it continue. So delete or make it comment break; line.

Upvotes: 1

Related Questions