How can I echo this PHP array with objects in an foreach loop?
I want to echo each value in different parts of my code.
array(2) {
["new_years_day"]=>
object(DateTime)#1 (3) {
["date"]=>
string(26) "2024-01-01 00:00:00.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(16) "America/New_York"
}
["juneteenth"]=>
object(DateTime)#2 (3) {
["date"]=>
string(26) "2024-06-19 00:00:00.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(16) "America/New_York"
}
}
I tried this code but it this doesn’t do the job ($holidaysThisYear is the name of the array):
<?php foreach($holidaysThisYear as $holidayThisYear) {
echo $holidayThisYear->timezone;
} ?>
2
Answers
When you works with you must to use the relevant class methods. In your case
getTimezone()
andgetName()
Play with PHP online
As per its documentation, the DateTime class doesn’t have any public properties.
You need to use the documented
getTimezone()
function instead, if you want to retrieve the timezone.Since the timezone it returns is itself an object and also has no public properties, you then need to use the
getName()
function from that class to get the timezone’s readable name.For example:
As you can see, this is all clearly laid out in the PHP documentation already.
Live demo: https://3v4l.org/hhqJU