PHP array add key and value
In PHP, key and value plays important role to create, access, and maintain an array. One key could be of String and numeric type where value could be of any type, it may be a string, numeric value, or boolean value.
Syntax of PHP array is "index=>value", this indices separated by comma, index values could be of any type. When index is omitted, an integer index is automatically assigned, starting at 0, the next positions will be automatically increased by +1. If you declare two identical indices then the last one will be overwrite the first one.
Example 1:
<?php
$array=array("Zero"=>0, 1=>"One","Two"=>2,1=>1,3=>true);
foreach($array as $value)
{
echo $value;
echo "";
}
print_r($array);
?>
Output:
1 2 1 Array ( [Zero] => 0 [1] => 1 [Two] => 2 [3] => 1 )
Example 2:
<?php
$array=array("New Delhi","Kolkata","Mumbai","Chennai");
echo "<b>Fourth Value is:</b>".$array[3]."<br/>";
echo "<br/><b>Each value of the array:</b><br/>";
foreach($array as $var)
{
echo $var."<br/>";
}
?>
Output:
Fourth Value is:Chennai
Each value of the array:
New Delhi
Kolkata
Mumbai
Chennai
Example 3:
<?php
$array=array("a"=>"apple","a"=>"australia");
foreach($array as $var)
echo $var;
$array=array(0=>"Zero", 0=>"NULL");
foreach($array as $var)
echo "<br/>".$var;
?>
Output:
australia
NULL
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.