1

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.

1

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

You can omit lowercase or uppercase letters from your array and cast given key to lower/uppercase letters. For example drop lowercase values and your array will look like this

$myArray =    [
    'JAN' => '01',
    'FEB' => '02',
    'MAR' => '03',
    'APR' => '04',
    'MAY' => '05',
    'JUNE' => '06',
    'JUL' => '07',
    'AUG' => '08',
    'SEPT' => '09',
    'OCT' => '10',
    'NOV' => '11',
    'DEC' => '12'

];

to get value from array use strtoupper()

 $key = 'mar';
 $month = $myarray[strtoupper($key)]; // $month = '03'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.