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

PhpArraysObject

Php Problem Overview


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) - 1]->name = "my name"; //modifies the element I just added

The above is functional, but is there a cleaner and more-readable way to write that? Maybe one line?

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

Here is a clean method I've discovered:

$myArray = [];

array_push($myArray, (object)[
        'key1' => 'someValue',
        'key2' => 'someValue2',
        'key3' => 'someValue3',
]);

return $myArray;

Solution 3 - Php

Do you really need an object? What about:

$myArray[] = array("name" => "my name");

Just use a two-dimensional array.

Output (var_dump):

array(1) {
  [0]=>
  array(1) {
    ["name"]=>
    string(7) "my name"
  }
}

You could access your last entry like this:

echo $myArray[count($myArray) - 1]["name"];

Solution 4 - Php

Something like:

class TestClass {
private $var1;
private $var2;

private function TestClass($var1, $var2){
	$this->var1 = $var1;
	$this->var2 = $var2;
}

public static function create($var1, $var2){
	if (is_numeric($var1)){
		return new TestClass($var1, $var2);
	}
	else return NULL;
}
}

$myArray = array();
$myArray[] = TestClass::create(15, "asdf");
$myArray[] = TestClass::create(20, "asdfa");
$myArray[] = TestClass::create("a", "abcd");

print_r($myArray);

$myArray = array_filter($myArray, function($e){ return !is_null($e);});

print_r($myArray);

I think that there are situations where this constructions are preferable to arrays. You can move all the checking logic to the class.

Here, before the call to array_filter $myArray has 3 elements. Two correct objects and a NULL. After the call, only the 2 correct elements persist.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionadamdportView Question on Stackoverflow
Solution 1 - PhphalferView Answer on Stackoverflow
Solution 2 - PhpahinkleView Answer on Stackoverflow
Solution 3 - PhpFrederik KammerView Answer on Stackoverflow
Solution 4 - PhpMoisés MárquezView Answer on Stackoverflow