How to push values with keys in to an array?


I have a set of values which has been queried from a database and i want it to be stored into a PHP array.

The query will return an set of values like this,

ADMIN_LABEL Administration

I using the following code to push content into the array,

$docdet = $docobj->exe_query("some query");
$num_rows = mysql_num_rows($docdet);
		$lang[] = $row['content'];


the result will be ,

[1] => Administration )

But the i want the array as

[‘ADMIN_LABEL’] => Administration )

array_push($lang['title'], $row['content']);	 // Even this is not working fine.

Associative arrays are defined

$array['index'] = $value'

The reason why your code isn’t working is because you haven’t defined an index, therefore PHP defaults to numeric indexes.

array_push($lang[$row['title']], $row['content']);	  	

i used the above code but it worked strange,

when i printed the array, the array has empty values, the array was like this,


But i’m sure that the $row[‘content’] is rendering values. why this is happening?

It’s not strange at all.

$lang[$row['title']] = $row['content'];

// is of the form

$array['index'] = $value';

$row[‘title’] is being set as the index of the array $lang.

When i use the following code ,

array_push($lang[$row['title']], $row['content']);	  	

the following warning is displayed but the array is filled with proper keys but empty values.

Warning: array_push() [function.array-push]: First argument should be an array

But when is i use

array_push($lang, $row['content']);	  	

the values are properly inserted into the array with the numeric indices.

How can i get it with proper keys and values?

any answers? Still waiting for one!

$lang[$row[‘title’]] = $row[‘content’];

You can’t use array_push to construct associative arrays.

You don’t need to use array_push at all. Just use the code that several other people have posted.

$lang[$row['title']] = $row['content'];

cant u use



No, that will fetch a whole row as an associative array, not a set of results.

Thanks Stormrider. that worked great. but i read from the site on the function reference guide that to push values with keys we can use the format which i used. That’s why i posted this question.

array_push doesn’t support that. I’m looking at the page now, and there is no mention of adding values with keys. Where are you looking?

I see it, in the comments someone posts that you can do:

array_push($data[$key], $value);

but it doesn’t work. The first parameter needs to be an array, and $data[$key] is not an array.

Or, if it IS an array, it’s the wrong array.