Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push both value and key into PHP array

Tags:

arrays

php

Take a look at this code:

$GET = array();     $key = 'one=1'; $rule = explode('=', $key); /* array_push($GET, $rule[0] => $rule[1]); */ 

I'm looking for something like this so that:

print_r($GET); /* output: $GET[one => 1, two => 2, ...] */ 

Is there a function to do this? (because array_push won't work this way)

like image 304
Gal Avatar asked Jan 23 '10 00:01

Gal


People also ask

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

Just assign $array[$key] = $value; It is automatically a push and a declaration at the same time.

Which array has pair of value and key in PHP?

In PHP, there are three types of arrays: Indexed arrays - Arrays with numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.

How get key from value in array in PHP?

If you have a value and want to find the key, use array_search() like this: $arr = array ('first' => 'a', 'second' => 'b', ); $key = array_search ('a', $arr); $key will now contain the key for value 'a' (that is, 'first' ).

What is array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.


1 Answers

Nope, there is no array_push() equivalent for associative arrays because there is no way determine the next key.

You'll have to use

$arrayname[indexname] = $value; 
like image 174
Pekka Avatar answered Oct 17 '22 14:10

Pekka