Home Tutorial Php Phpbasics PHP Array Push Key Value

 
 

PHP Array Push Key Value
Posted on: October 23, 2009 at 12:00 AM
Advertisement
PHP Array Push Key Value: This tutorial illustrates the concept of array_push(), it also includes what can not be associated with value of an array after applying array_push() function, this tutorial also discussed about the associative array in brief.

PHP Push Key Value

In PHP whenever you need to use array_push() function you have to use only the value, because array_push() function does not allow the key part of an associative array. In numeric array, the index position is start from 0, the second is index position is 1 and so on. PHP supports associative array, in which we can associate any kind of key (generally string or numeric) with a value.Sometimes it is more beneficial to have String keys or indexes in an array instead of numeric keys. For instance if you want to store the salary of  employee or the marks obtained by the students, then it will be more beneficial to use associative array instead of using numeric array.

$array=array("City"=>"New Delhi", "State"=>"Delhi"," Pin"=>110029)

Like the numerically indexed array we can create and initialize an associative array with one element at a time. Following example will help you to understand this concept:

In array_push() function key is automatically assigned, like in the following case:

Example 1:

<?php

$array=array(0=>"Zero",1=>"One",2=>"Two");

echo "<b>Initially the values of array is:</b><br/>";

print_r($array);

array_push($array,"Three","Four");

echo "<br/><b>After pushing some values,the array become:</b><br/>";

print_r($array);

?>

Output:

Initially the values of array is:
Array ( [0] => Zero [1] => One [2] => Two )
After pushing some values,the array become:
Array ( [0] => Zero [1] => One [2] => Two [3] => Three [4] => Four )

 

array_push() function always append a numeric key with any kind of value, if we associated string keys with numeric values, after using array_push() function further keys will be in numeric, the following example illustrates that:

 Example 2:

<?php

$array=array("Zero"=>0,"One"=>1,"Two"=>2);

echo "<b>Initially the values of array is:</b><br/>";

print_r($array);

array_push($array,3,4);

echo "<br/><b>After pushing some values,the array become:</b><br/>";

print_r($array);

?>

Output:

Initially the values of array is:
Array ( [Zero] => 0 [One] => 1 [Two] => 2 )
After pushing some values,the array become:
Array ( [Zero] => 0 [One] => 1 [Two] => 2 [0] => 3 [1] => 4 )

Advertisement

Related Tags for PHP Array Push Key Value:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 23, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com