skip to Main Content

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


  1. When you works with you must to use the relevant class methods. In your case getTimezone() and getName()

    <?php
    $holidaysThisYear = [
        "new_years_day" => new DateTime("2024-01-01 00:00:00.000000"),
        "juneteenth" => new DateTime("2024-06-19 00:00:00.000000")
    ];
    
    
    foreach($holidaysThisYear as $holidayThisYear) {
        echo $holidayThisYear->getTimezone()->getName();
        echo PHP_EOL;
    }
    

    Play with PHP online

    Login or Signup to reply.
  2. 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:

    echo $holidayThisYear->getTimezone()->getName();
    

    As you can see, this is all clearly laid out in the PHP documentation already.

    Live demo: https://3v4l.org/hhqJU

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search