- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
In PHP, how can I add an object element to an array?
The code is as follows −
Example
$object = new stdClass(); $object->name = "My name"; $myArray[] = $object;
Output
This will produce the following output −
Suppose myArray already contains ‘a’ and ‘c’, the value of “My name” will be added to it. It becomes Array { a:0, c:1, “My name”:2 }
The object is created and then it is pushed to the end of the array (that was previously present).
Alternative
$myArray[] = (object) ['name' => 'My name'];
Advertisements