array as a variable php code example

Example 1: php declare array

// sequential array
$arr = array(
  'v1',		// $arr[0] == 'v1'
  'v2',		// $arr[1] == 'v2'
  'v3'		// $arr[2] == 'v3'
);
// or (since PHP 5.4)
$arr = [
  'v1',		// $arr[0] == 'v1'
  'v2',		// $arr[1] == 'v2'
  'v3'		// $arr[2] == 'v3'
];

// key accessed array (map like)
$arr = array(
  'k1' => 'v1',		// $arr['k1'] == 'v1'
  'k2' => 'v2',		// $arr['k2'] == 'v2'
  'k3' => 'v3'		// $arr['k3'] == 'v3'
);
// or (since PHP 5.4)
$arr = [
  'k1' => 'v1',		// $arr['k1'] == 'v1'
  'k2' => 'v2',		// $arr['k2'] == 'v2'
  'k3' => 'v3'		// $arr['k3'] == 'v3'
];

Example 2: assign array to variable php

$info = array('coffee', 'brown', 'caffeine');

// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";

// Listing some of them
list($drink, , $power) = $info;
echo "$drink has $power.\n";

// Or let's skip to only the third one
list( , , $power) = $info;
echo "I need $power!\n";

// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar); // NULL

Tags:

Php Example