PHP: Populating an array with the names of the next 12 months
Just fixed your code slightly, this should work pretty well:
$months = array();
$currentMonth = (int)date('m');
for ($x = $currentMonth; $x < $currentMonth + 12; $x++) {
$months[] = date('F', mktime(0, 0, 0, $x, 1));
}
Note that I took out the array key, as I think it's unnecessary, but you can change that of course if you need it.
How to list the last N months with PHP DateTime
You are getting same 2 months, because when you are subtracting 1 month from date, that has more days than previous month. Example: when you subtract 1 month from 31.3. you will get 3.3. (same month), and not 28.2. as you might expect...
My suggestion is to get first day of current month, and then do your logic:
$dt = new DateTime('first day of this month');
for ($i = 1; $i <= 10; $i++) {
echo $dt->format('F Y'), "\n";
$dt->modify('-1 month');
}
demo
Get the last 12 months in PHP
I'm sure someone has a more elegant solution, but you could start counting backwards from the 1st of this month.
for ($i = 1; $i <= 12; $i++) {
$months[] = date("Y-m%", strtotime( date( 'Y-m-01' )." -$i months"));
}
Populating PHP list() with values in an array
You are trying to use a language construct in a manner in which it's not meant to be used. Use variable variables as Alvaro mentioned.
$arr = array('foo', 'bar', 'bash', 'monkey', 'badger');
foreach ($arr as $index => $key) {
$$key = $data[$index];
}
or
$arr = array('foo', 'bar', 'bash', 'monkey', 'badger');
$result = array();
foreach ($arr as $index => $key) {
$result[$key] = $data[$index];
}
extract($result);
In short, do not use "list", use arrays and associated arrays. Write helper functions to make your code clearer.
Creating an array of dates with a sequence of intervals between days
Carbon is perfectly able to do this:
// $startDate as mentioned should be a valid Carbon date pointed to Tuesday
$dates = [];
for ($currentDate = $startDate; $currentDate <= $endDate; ) {
$dates[] = $currentDate;
$currentDate->addDays(2);
$dates[] = $currentDate;
$currentDate->addDays(2);
$dates[] = $currentDate;
$currentDate->addDay();
}
Insert new datas into an existing array in PHP
One way to do this is
$yourArray[1] = 149.0;
$yourArray[3] = 1166.0;
$months = range(1, 12);
foreach (array_keys($yourArray) as $month) {
unset($months[$month - 1]);
}
foreach ($months as $month) {
$yourArray[$month] = 0.00;
}
- With
range
you are basically creating ad array with value from 1 to 12. - Next
foreach
will loop upon your array keys and unset previously setted months, leaving other without a value. The-1
part is due to zero index of array - Final
foreach
will set to0.00
remaining values
Populate array by recycling a smaller array starting with a particular value
You have supplied the lookup array, the number of iterations, and the value before the starting value.
The only things left to do are:
- Find the count of the lookup,
- Find the index of the last value in the lookup,
- Loop the expressed number of times,
- Use a modulus calculation to find the next appropriate value in the lookup, and
- Push values into the result array.
This can be done with no iterated function calls.
Code: (Demo)
$count = count($list_order_id);
$index = array_search($last_id, $list_order_id);
$result = [];
for ($i = 0; $i < $vacancies; ++$i) {
$result[] = $list_order_id[++$index % $count];
}
var_export($result);
Populate array of class type in PHP
Just simply add new Fuelprices($year, $coal)
objects into the array.
foreach($arrayFromDatabase as $theData){
$data[] = new Fuelprices($theData['year'], $theData['coal']);
}
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).
Fill array with values without loop in PHP
use array_fill()
:
$t = array_fill(0, $n, 'val');
Related Topics
Laravel Collection Converts Array to Object
Get Number of Weekdays in a Given Month
Generating a Random Code in PHP
Set Httponly and Secure on PHPsessid Cookie in PHP
PHP - How to Get Shell Errors Echoed Out to Screen
PHP Session Variables Not Preserved with Ajax
PHP - Syntax Error, Unexpected T_Constant_Encapsed_String
Why Does an Infinitely Recursive Function in PHP Cause a Segfault
Laravel Form Methods VS Traditional Coding
Why Does (0 == 'Hello') Return True in PHP
Set_Error_Handler() Doesn't Work for Fatal Error
PHP Function to Replace a (I)Th-Position Character
How to Stop Curl from Using 100 Continue
Perl Equivalent of PHP's Escapeshellarg
Undefined Offset When Using PHP Explode()