Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP push new key and value in existing object array

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?

like image 959
Dinizworld Avatar asked May 28 '14 15:05

Dinizworld


People also ask

How do you push a key and value in an array?

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); ?>

What is array_push in PHP?

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).

Can you push an array into an array PHP?

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.


2 Answers

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";
like image 78
Mark Baker Avatar answered Oct 05 '22 23:10

Mark Baker


You can simply use $html_doc["title"] = "testtitle";

Check this comment on the array_push manual page.

like image 45
Jaaz Cole Avatar answered Oct 05 '22 23:10

Jaaz Cole