Click here to Skip to main content
15,921,660 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm making a function to check the month is valid or not. For eg.

PHP
checkMonth("Feb") => true
checkMonth("Mar") => true
checkMonth(02) => true
checkMonth(2) => true


But

PHP
checkMonth("X") => false
checkMonth("XYZ") => false


There is no issue in the numeric form 2 or 02. But if I'm passing argument like "X" or "XYZ" its not working and returns true.

Im trying

PHP
echo date('n', strtotime("XYZ"));


which is returning true because the value of date('n', strtotime("XYZ")) is 3 which is a valid month.

I also tried

PHP
$mon=date_format(date_create("XYZ"),"n");


But it has the same affect.
Posted

Try this idea: put all the month names in an array, then use in_array function to check:
http://php.net/manual/en/function.in-array.php[^]
+++++[Round 2]+++++
ok, try strtotime()[^]
e.g.
PHP
if (strtotime('Jun'))
    echo 1;
else
    echo 0;
 
Share this answer
 
v3
Comments
Samartha Sinha 13-Mar-15 4:59am    
That can be one way of doing it. But isn't there any function in php that can check the string is valid month or not?
Peter Leow 13-Mar-15 6:31am    
use strtotime, added in solution.
Samartha Sinha 13-Mar-15 6:43am    
I've done that its not working.
Peter Leow 13-Mar-15 7:00am    
Test my example code on any free online php test tool such as http://phptester.net/
Samartha Sinha 13-Mar-15 7:19am    
If you do
if (strtotime('X'))
echo 1;
else
echo 0;
The result is 1
But it should be 0
You could simply list all of your possible good answers in a switch statement with a fall-through and anything else fails.

Example:

PHP
switch($isMonth) {
  case 'JAN':
  case  1:
  case '01':
  case 'FEB': 
     etc etc etc.
           return 1;
           break; // Not really needed after a return statement but it's a habit.
  default:  return 0
} // 


You may want to convert $isMonth to upper case or lower case before your test or you'll need to include every variation.

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900