I'm having some trouble figuring out how to get an array item with a $variable - 1
.
What I am trying to do:
I have an array of days in a month
$monthsArray = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
I have a variable which is the month
$monthOfDeparture = mb_substr($departureDate, 3, 4);
which has the value of 01 for January etc.
I am trying to get the correct month by
$theMonth = $monthsArray[$monthOfDeparture - 1]
What I actually get is the month of departure ie: March (31) instead of February (28) if $monthOfDeparture = 03
.
Any help would be welcome.
Providing code: note the $arrivalDate
and $departureDate
look like this 23-02-21
(dd-mm-yy)
$arrivalDateNumber = mb_substr($arrivalDate, 0, 1);
$departureDateNumber = mb_substr($departureDate, 0, 1);
$monthOfArrival = mb_substr($arrivalDate, 3, 4);
$monthOfDeparture = mb_substr($departureDate, 3, 4);
$monthsArray = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if( $departureDateNumber < $arrivalDateNumber) {
$depNumTwo = $monthsArray[$monthOfDeparture - 1];
$lodgingNights = $depNumTwo - $arrivalDateNumber + $departureDateNumber;
$pay = $lodgingNights * $price_per_night;
}else{
$lodgingNights = $departureDateNumber - $arrivalDateNumber;
$pay = $lodgingNights * $price_per_night;
}
Edit
There was an error my logic. What I wanted to do was:
// if the number of days in departure is greater then the number of days in arrival
if( $departureDateNumber < $arrivalDateNumber) {
//get the number of days in the month of arrival
$arrNumTwo = $monthsArray[$monthOfArrival];
//the user will stay: total number of days in arrival month - starting date of arrival + days in the next month
$lodgingNights = $arrNumTwo - $arrivalDateNumber + $departureDateNumber;
$pay = $lodgingNights * $price_per_night;
}else{
$lodgingNights = $departureDateNumber - $arrivalDateNumber;
$pay = $lodgingNights * $price_per_night;
}
The problem I am having now is that I get Notice: Undefined index: 02-2 in my path on line $arrNumTwo = $monthsArray[$monthOfArrival];
I guess that is becouse of this code segment $monthOfArrival = mb_substr($arrivalDate, 3, 4);
although I don't know why it dosesn't just take the 3rd and 4th character.
Edit nmb xy.
Figured out I misnderstood how substr works. Needed to use $monthOfArrival = mb_substr($arrivalDate, 3, 2);