Home > Net >  How to find a string contained in an array?
How to find a string contained in an array?

Time:12-01

I have 2 arrays:

  • $DatesToDelete()
  • $ArrayAllDates()

$DatesToDelete() contains a list of dates, like this:

01/11/2022 02/11/2022 03/11/2022 04/11/2022 05/11/2022 06/11/2022 07/11/2022 08/11/2022 09/11/2022 10/11/2022 11/11/2022 12/11/2022 13/11/2022 14/11/2022 15/11/2022 16/11/2022 17/11/2022 18/11/2022 19/11/2022 20/11/2022 21/11/2022 22/11/2022 23/11/2022 24/11/2022 25/11/2022 26/11/2022 27/11/2022 28/11/2022 29/11/2022 30/11/2022

$ArrayAllDates() contains another list of dates, like this:

07/11/2022 07/11/2022 18/11/2022 17/11/2022 02/12/2022

**My goal is to find if dates coming from $DatesToDelete() are contained in $ArrayAllDates() **

I'm not a PHP expert and I tried a lot of loops with foreach() without success :-(

Thank you

foreach($ArrayAllDates as $d) {
    foreach($DatesToDelete as $e) {
       if(in_array($b,$arrayalldates)){
       }
    }
}

CodePudding user response:

As @DCodeMania said, you can use the array_intersect function (https://www.php.net/manual/en/function.array-intersect.php).

For example:

$datesToDelete = [
    '02/11/2022',
    '04/11/2022',
    '06/11/2022',
    '07/11/2022',
    '02/12/2022',
];
$allDates = [
    '07/11/2022',
    '07/11/2022',
    '18/11/2022',
    '17/11/2022',
    '02/12/2022',
];
$commonDates = array_intersect($allDates, $datesToDelete);
print_r($commonDates);
/* it print this:
Array
(
    [0] => 07/11/2022
    [1] => 07/11/2022
    [4] => 02/12/2022
)
when the key is de key and value are of $allDates array
*/

CodePudding user response:

you can use this looping

foreach($ArrayAllDates as $d){
  if(in_array($d, $DatesToDelete)){
    echo $d."<br>";
  }
}

if you want save this contain date to array

$containDates = array();
foreach($ArrayAllDates as $d){
  if(in_array($d, $DatesToDelete)){
    array_push($containDates ,$d);
  }
}
print_r($containDates);
  •  Tags:  
  • php
  • Related