0

I am having a problem with this code:

$days = array();
$d = new StdClass;
for($i = 0; $i < 7; $i++){
    $day = date("Y-m-d", strtotime("-".$i." day"));
    $d->x = $day; //error
    $days[] = $d;
    unset($d);
}
dd($days);

Even thought I have declared a new object it shows me error:

Creating default object from empty value.

How could i possibly resolve this problem?

3
  • what is your expected output? Commented May 2, 2017 at 18:25
  • An array full of objects. It's simplified so not only "x" will be an attribute. It worked just perfectly in plain php Commented May 2, 2017 at 18:26
  • 3
    Possible duplicate of Creating default object from empty value in PHP? Commented May 3, 2017 at 4:03

1 Answer 1

1

Try this, Hope this will help you out. You should define $d = new StdClass; with in the loop. For initiating a new object everytime.

Try this code snippet here

<?php

ini_set('display_errors', 1);
$days = array();
for ($i = 0; $i < 7; $i++)
{
    $d = new StdClass;
    $day = date("Y-m-d", strtotime("-" . $i . " day"));
    $d->x = $day; //error
    $days[] = $d;
    unset($d);
}
print_r($days);
Sign up to request clarification or add additional context in comments.

1 Comment

Defining it in the loop did the thing. Thank you. Will mark as an answer after delay

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.