ShanjayG
ShanjayG

Reputation: 1023

PHP good way to extract month's 3 initial letter from an array of strings

I have

$array = array(
  'AUS200JAN',
  'GOLD300MAR',
  'AUS200_h18',
  'GOLD300_g19',
  'EURUSDJUL18',
  'AUSEURNOV18',
);

I would like to know an efficient way to find out if the array values contain the initial 3 letters of a month. So in this array there JAN, MAR, JUL18, NOV18.

So far I am doing it this way but would like to know if there is a more efficient way to approach this problem.

//Creating an Array of letters for months
$montharray = array(
   'JAN','FEB','MAR','APR',''MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'
);

foreach($montharray as $month) {
    foreach($array as $val) {
       if(strpos($val,$month) !== FALSE) {
           var_dump('has month');
       } else {
           var_dump('Does not contain month');
       }
    }
}

Upvotes: 0

Views: 49

Answers (1)

pr1nc3
pr1nc3

Reputation: 8338

<?php

$array = array(
    'AUS200JAN',
    'GOLD300MAR',
    'AUS200_h18',
    'GOLD300_g19',
    'EURUSDJUL18',
    'AUSEURNOV18',
);

$months = array();
for ($i = 0; $i < 12; $i++) {
    $timestamp = mktime(0, 0, 0, date('f') - $i, 1);
    $months[date('n', $timestamp)] = date('M', $timestamp);

}

echo '<pre>';
print_r($months);


foreach($months as $row){
    if(preg_grep( "/$row/i" , $array )){
        echo 'found';
        echo '</br>';
    }
    else{
        echo 'not found';
        echo '</br>';
    }
}

You can try something like this. It checks the array records for each month (3 letters format)

Upvotes: 1

Related Questions