$oldm='5';
I want $oldm to convert to a new variable $newm, so that $newm contains "may". I mean i want to convert $oldm to text month. How to do it ?

Dani AI

Generated

— two quick notes on the answers already here: 's array is the simplest when you want fixed, custom labels; 's date/strtotime trick is handy but builds a fake date string. If you want a concise, reliable alternative that avoids hand-maintained arrays and string fiddling, use PHP's DateTime APIs; for localization use the intl extension.

A compact, robust approach with DateTime::createFromFormat:

$oldm = '5';
$dt = DateTime::createFromFormat('!m', $oldm);
if ($dt === false) {
    // handle invalid month input
}
$newm = strtolower($dt->format('F')); // "may"

The leading ! resets other fields so the month parse is deterministic; check for false (invalid input). See DateTime::createFromFormat and DateTime::format.

If you need locale-aware month names, prefer IntlDateFormatter (requires the intl extension / ICU):

$dt = DateTime::createFromFormat('!m', $oldm);
$fmt = new IntlDateFormatter('fr_FR', IntlDateFormatter::LONG, IntlDateFormatter::NONE, 'UTC', IntlDateFormatter::GREGORIAN, 'MMMM');
$newm = $fmt->format($dt); // full month name in French

See IntlDateFormatter and ensure extension_loaded('intl').

Best practices: always cast/validate the input (1..12), decide whether you want custom labels (use an array) or localized names (use Intl), and use strtolower() only when you need lowercase. Avoid strftime() for new code — it is locale-based but deprecated in recent PHP versions. See strftime for details.

Recommended Answers

All 2 Replies

Create an array with all the months in it. Then if 5 is supplied as the month, just access the 5th element of the array.

You may want to put a dummy value in location 0 of the array so it makes it a bit easier to access the correct array key. E.g.

$months = array('dummy','Jan','Feb','Mar','April','May','June','July','Aug','Sept','Oct','Nov','Dec');

$oldm = 5;
$newm = $months[$oldm];

Use this, you won't have to type up the months. This creates a string '5/1/2010' and then converts it to a timestamp, and passes it into the date function with the 'F' as the format, which will output the text version of the month.

$oldm = 5;
$newm = date( 'F', strtotime( $oldm . '/1/' . date('Y') ) );

doing it this way makes it easier to maintain. If you later want to change to month abbreviations, you could just change 'F' to 'M', no changing an array of months.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.