tags:

views:

374

answers:

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

thanks!

+2  A: 

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;
Pekka
thanks, i'll use this then.
sombe
A: 
$GET[ $rule[0] ] = $rule[1];
Bill Karwin
A: 

Exactly what Pekka said...

Alternatively, you can probably use array_merge like this if you wanted:

array_merge($_GET, array($rule[0] => $rule[1]));

But I'd prefer Pekka's method probably as it is much simpler.

pssdbt
A: 

I was just looking for the same thing and I realized that, once again, my thinking is different because I am old school. I go all the way back to BASIC and PERL and sometimes I forget how easy things really are in PHP.

I just made this function to take all settings from the database where their are 3 columns. setkey, item (key) & value (value) and place them into an array called settings using the same key/value without using push just like above.

Pretty easy & simple really


// Get All Settings
$settings=getGlobalSettings();


// Apply User Theme Choice
$theme_choice = $settings['theme'];

.. etc etc etc ....




function getGlobalSettings(){

    $dbc = mysqli_connect(wds_db_host, wds_db_user, wds_db_pass) or die("MySQL Error: " . mysqli_error());
    mysqli_select_db($dbc, wds_db_name) or die("MySQL Error: " . mysqli_error());
    $MySQL = "SELECT * FROM systemSettings";
    $result = mysqli_query($dbc, $MySQL);
    while($row = mysqli_fetch_array($result)) 
        {
        $settings[$row['item']] = $row['value'];   // NO NEED FOR PUSH
        }
    mysqli_close($dbc);
return $settings;
}


So like the other posts explain... In php there is no need to "PUSH" an array when you are using

Key => Value

AND... There is no need to define the array first either.

$array=array();

Don't need to define or push. Just assign $array[$key] = $value; It is automatically a push and a declaration at the same time.

I must add that for security reasons, (P)oor (H)elpless (P)rotection, I means Programming for Dummies, I mean PHP.... hehehe I suggest that you only use this concept for what I intended. Any other method could be a security risk. There, made my disclaimer!

Cory Cullers
+1  A: 

Pushing a value into an array automatically creates a numeric key for it.

When adding a key-value pair to an array, you already have the key, you don't need one to be created for you. Pushing a key into an array doesn't make sense. You can only set the value of the specific key in the array.

// no key
array_push($array, $value);
// same as:
$array[] = $value;

// key already known
$array[$key] = $value;
deceze