In PHP given a month string such as November how can I return 11 without using a 12 part switch statement?
Try
echo date('n', strtotime('November')); // returns 11
If you have to do this often, you might consider using an array that has these values hardcoded:
$months = array( 1 => 'January', 2 => 'February', 3 => 'March', 4 => 'April',
5 => 'May', 6 => 'June', 7 => 'July', 8 => 'August',
9 => 'September', 10 => 'October', 11 => 'November',
12 => 'December');
Can also do it the other way round though, using the names for the keys and numbers for values.
With the names for values you do
echo array_search('November', $months); // returns 11
and with names for keys you do
echo $months['November']; // returns 11
I find using the numbers for the keys somewhat better in general, though for your UseCase the names for keys approach is likely more comfortable. With just 12 values in the array, there shouldn't be much of a difference between the array approches.
A quick benchmark noted a difference of 0.000003s vs 0.000002s, whereas the time conversion takes 0.000060s on my computer (read: might differ on other computer).
PHP convert month
<?php echo date("F",mktime(0,0,0,$member['dob_month'],1,0); ?>
How can I convert month name to number?
$monthName = 'January';
$date = date_parse($monthName);
$monthNumber = $date['month'];
Note that this will return 1
, not 01
, so change your display format accordingly.
Use an array of ordered date expressions to populate a new array with data from a second array related by its numeric keys
Use array_map()
to map the numeric data to the month-year expression. To relate the data's numeric keys to the date expressions, use a datetime class plus a convert method, or just call date(strtotime())
.
Code: (Demo) (Classic loop)
var_export(
array_map(
fn($My) => $data[date('n', strtotime($My))],
$forecastedMonths
)
);
Very relevant page: In PHP given a month string such as "November" how can I return 11 without using a 12 part switch statement?
How to translate specific set of strings in PHP
An array would be useful here, and in this case it would be similar to a hashmap in Java.
$wkday = "Thu";
$wkdayMapper = array(
"Mon" => "Monday",
"Tue" => "Tuesday",
"Wed" => "Wednesday",
"Thu" => "Thursday",
"Fri" => "Friday",
"Sat" => "Saturday",
"Sun" => "Sunday"
);
echo $wkdayMapper[$wkday]; //Thursday
PHP manual link on arrays
How to shorten switch case block converting a number to a month name?
Define an array, then get by index.
var months = ['January', 'February', ...];
var month = months[mm - 1] || '';
Calculate the number of months between two dates in PHP?
$date1 = '2000-01-25';
$date2 = '2010-02-20';
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$year1 = date('Y', $ts1);
$year2 = date('Y', $ts2);
$month1 = date('m', $ts1);
$month2 = date('m', $ts2);
$diff = (($year2 - $year1) * 12) + ($month2 - $month1);
You may want to include the days somewhere too, depending on whether you mean whole months or not. Hope you get the idea though.
How do I check if a string contains a specific word?
Now with PHP 8 you can do this using str_contains:
if (str_contains('How are you', 'are')) {
echo 'true';
}
RFC
Before PHP 8
You can use the strpos()
function which is used to find the occurrence of one string inside another one:
$haystack = 'How are you?';
$needle = 'are';
if (strpos($haystack, $needle) !== false) {
echo 'true';
}
Note that the use of !== false
is deliberate (neither != false
nor === true
will return the desired result); strpos()
returns either the offset at which the needle string begins in the haystack string, or the boolean false
if the needle isn't found. Since 0 is a valid offset and 0 is "falsey", we can't use simpler constructs like !strpos($a, 'are')
.
Should switch statements always contain a default clause?
Switch cases should almost always have a default
case.
Reasons to use a default
1.To 'catch' an unexpected value
switch(type)
{
case 1:
//something
case 2:
//something else
default:
// unknown type! based on the language,
// there should probably be some error-handling
// here, maybe an exception
}
2. To handle 'default' actions, where the cases are for special behavior.
You see this a LOT in menu-driven programs and bash shell scripts. You might also see this when a variable is declared outside the switch-case but not initialized, and each case initializes it to something different. Here the default needs to initialize it too so that down the line code that accesses the variable doesn't raise an error.
3. To show someone reading your code that you've covered that case.
variable = (variable == "value") ? 1 : 2;
switch(variable)
{
case 1:
// something
case 2:
// something else
default:
// will NOT execute because of the line preceding the switch.
}
This was an over-simplified example, but the point is that someone reading the code shouldn't wonder why variable
cannot be something other than 1 or 2.
The only case I can think of to NOT use default
is when the switch is checking something where its rather obvious every other alternative can be happily ignored
switch(keystroke)
{
case 'w':
// move up
case 'a':
// move left
case 's':
// move down
case 'd':
// move right
// no default really required here
}
Related Topics
Macd Function Returning Incorrect Values
Http Header for Downloading Microsoft Word and Excel Files
PHP HTML Decoding Help - Converting: a 'Quote' Is <B>Bold</B>
Laravel Store Array in Session
Sort Array by Date in Descending Order by Date in PHP
In Flutter Web Getting 'Xmlhttprequest' Error While Making Http Call
How to Load the Requested Language File: Language/En/Form_Validation_Lang.Php
How to Get the First Day of the Week for the Current Locale? (Php/L8N)
Key of Null Variable Equals Null Not Error
Why Do I Receive "This Value Should Be of Type String" When Using a Datetime Constraint on Symfony 5
Pdo SQL-State "00000" But Still Error
Count Word Frequency in a Text
Laravel 5 - Session Doesn't Work