In my study how objects and arrays work with PHP I have a new problem. Searching in existing questions didn't give myself the right "push".
I have this for example:
$html_doc = (object) array
(
"css" => array(),
"js" => array()
);
array_push($html_doc , "title" => "testtitle");
Why is this not working? Do i need to specify first the key title? Or is there another "1 line" solution?
Answer: Use the Square Bracket [] Syntax php // Sample array $array = array("a" => "Apple", "b" => "Ball", "c" => "Cat"); // Adding key-value pairs to an array $array["d"] = "Dog"; $array["e"] = "Elephant"; print_r($array); ?>
Definition and Usage. The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).
You can add one element or multiple elements at a time using the array_push() function. The array_push() treats an array as a stack and pushes the passed variables onto an array's end.
array_push() doesn't allow you to specify keys, only values: use
$html_doc["title"] = "testtitle";
.... except you're not working with an array anyway, because you're casting that array to an object, so use
$html_doc->title = "testtitle";
You can simply use $html_doc["title"] = "testtitle";
Check this comment on the array_push manual page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With