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 )
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.