Search code examples
phparraysyii2yii2-advanced-app

Yii2 search array and find the matching value


I have created an array

  $myArray =    [
        'JAN' => '01',
        'jan' => '01',
        'FEB' => '02',
        'feb' => '02',
        'MAR' => '03',
        'mar' => '03',
        'APR' => '04',
        'apr' => '04',
        'MAY' => '05',
        'may' => '05',
        'JUNE' => '06',
        'june' => '06',
        'JUL' => '07',
        'jul' => '07',
        'AUG' => '08',
        'aug' => '08',
        'SEPT' => '09',
        'sept' => '09',
        'OCT' => '10',
        'oct' => '10',
        'NOV' => '11',
        'nov' => '11',
        'DEC' => '12',
        'dec' => '12',

    ];

The above array is inside my function. This function accepts a string. The string is the short form of a month and it can be any of the months in a year. So I want to search my input variable with the array provided that if it matched any of the given elements then it will return the month number.

How can I do this?

Any help would be highly appreciated.


Solution

  • To give another answer to this, you can just use the date functions, for example;

    $month_name = "march"; // or MARCH (case doesn't matter)
    $month_number = date("m", strtotime($month_name));
    echo $month_number; // echos 03
    

    You can also use short names for this, for example;

    $month_name = "mar"; // or MAR (case doesn't matter)
    $month_number = date("m", strtotime($month_name));
    echo $month_number; // echos 03
    

    This greatly reduces your need for arrays and dictionaries