In PHP, how can I add an object element to an array?

后端 未结 4 803
心在旅途
心在旅途 2020-12-05 09:25

I\'m using PHP. I have an array of objects, and would like to add an object to the end of it.

$myArray[] = null; //adds an element
$myArray[count($myArray) -         


        
4条回答
  •  -上瘾入骨i
    2020-12-05 10:03

    Just do:

    $object = new stdClass();
    $object->name = "My name";
    $myArray[] = $object;
    

    You need to create the object first (the new line) and then push it onto the end of the array (the [] line).

    You can also do this:

    $myArray[] = (object) ['name' => 'My name'];
    

    However I would argue that's not as readable, even if it is more succinct.

提交回复
热议问题