Array Add Key Value PHP


 

Array Add Key Value PHP

PHP Array Add Key Value: In this PHP tutorial we will get know about different ways to access key and value. Different examples will let you know about the index and values.keep studying..

PHP Array Add Key Value: In this PHP tutorial we will get know about different ways to access key and value. Different examples will let you know about the index and values.keep studying..

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/>";

0

 

}

?>

1

Output:

Fourth Value is:Chennai

Each value of the array:
New Delhi
Kolkata
Mumbai
Chennai

2

Example 3:

<?php

3

$array=array("a"=>"apple","a"=>"australia");

foreach($array as $var)

4

echo $var;

5

$array=array(0=>"Zero", 0=>"NULL");

foreach($array as $var)

6

echo "<br/>".$var;

?>

7

Output:

australia
NULL

8

Ads