Various Array Operations in PHP

An array can be created using the array() language construct. It takes any number of comma-separated key => value pairs as arguments.

array(

    key  => value,

    key2 => value2,

    key3 => value3,

    …

)

The comma after the last array element is optional and can be omitted. This is usually done for single-line arrays, i.e. array(1, 2) is preferred over array(1, 2, ).


 

Step 1 : Creation

<?php

$array = array(

    "key1" => "value1",

    "key1" => "value2",

);

// as of PHP 5.4

$array = [

    "key1" => "value1",

    "key1" => "value2",

];

?>


Step 2 : Iteration

<?php

  echo "Value : " . $arr[2];

?>

<?php

$arr = array(1, 2, 3, 4);

foreach ($arr as &$value) {

    $value = $value * 2;

}

// $arr is now array(2, 4, 6, 8)

unset($value); // break the reference with the last element

?>

<?php

foreach ($arr as $key => $value) {

    echo "Key: $key; Value: $value<br />\n";

}

?>


Step 3 Sorting

<?php

$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");

ksort($fruits);

foreach ($fruits as $key => $val) {

    echo "$key = $val\n";

}

?>


 

 

You can leave a response, or trackback from your own site.

Leave a Reply