在php中关闭数组元素中添加更多键值[关闭]

在php中关闭数组元素中添加更多键值[关闭]

问题描述:

Lets say I have an array which has the first element like

Array ( [name] => gaurav pandey [education] => MCA )

Now I want to insert some more properties so the end result should be like:

Array ( [name] => gaurav pandey [education] => MCA [occupation] => developer [passion] => programming)

How can I achieve that in php? I have seen the dynamic creation of instances and their properties but still can't figure out how to achieve it in php array.

I'm pretty sure you're just asking how to insert a new key/value into an array, which is an incredibly basic PHP syntax question.

See the manual, specificall Creating/modifying with square bracket syntax:

To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the unset() function on it.

 <?php
 $arr = array(5 => 1, 12 => 2);

 $arr[] = 56;    // This is the same as $arr[13] = 56;
                // at this point of the script

 $arr["x"] = 42; // This adds a new element to
                // the array with key "x"

 unset($arr[5]); // This removes the element from the array

 unset($arr);    // This deletes the whole array
 ?>

The syntax for adding properties to an array:

$a = array (
    "name" => "gaurav pandey",
    "education" => "MCA"
);
$a["occupation"] = "developer";
$a["passion"] = "programming"

You should start by reading the PHP Manual about Arrays first. And check this example:

// create the associative array:
$array = array(
    'name' => 'gaurav pandey'
);

// add elements to it
$array ['education'] = 'MCA';
$array ['occupation'] = 'Developer';

in addition to @meagar's post, id also suggest taking a look at the array_functions pages in the php manual:

http://php.net/manual/en/ref.array.php

eg, combining arrays, traversing arrays, sorting arrays, etc.

you can also merge arrays

<?php
$array1 = array("name" => "gaurav pandey","education" => "MCA");
$array2 = array("color" => "green", "shape" => "trapezoid", "occupation" => "developer", "passion" => "programming");
$result = array_merge($array1, $array2);
print_r($result);
?>

You can also use array_push() too. This is handy if you're adding more than one item at once to the array but has a little overhead attached.