Arrays in PHP

Posted under » PHP on 13 March 2009

Array Fundamentals
To work with arrays, you need to learn two new terms: elements and indexes.

You can think of an array like a spreadsheet that has only two columns. The first column (or key) uniquely identifies the row in the spreadsheet, while the second column contains a stored value. I use array like an inline database.

Associative Versus Numeric Indexed Arrays
Numeric arrays use numbers as their indexes, while associative arrays use strings. When using associative arrays, you must supply an index string each time you add an element. Numeric arrays allow you to just add the element, and PHP automatically assigns the first free number, starting at 0. Both types of arrays allow you to add new elements to the array one at a time. Associative arrays are nice for storing configuration data since their keys can have a meaningful name.

Numeric Indexed Arrays is quite common so here is an example of associative arrays.

 define array
$camera = array (
"canon" => array("pro" => "1D", "full frame" => "5D", "prosumer" => "50D"),
"nikon" => array("pro" => "D3", "full frame" => "D700", "prosumer" => "D90"),
);
// Echo this out:
print_r($camera);

If you just want to show Canon Prosumer camera model which is 50D

echo  $camera["canon"]["prosumer"];

Assignment of values via array identifiers for Numeric Indexed Arrays

<¿php
$weekdays[] = 'Monday';
$weekdays[] = 'Tuesday';
?>

or <¿php
$weekdays = array('Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday');
?>

You can check if a value exists in an array with the in_array command without the need to loop

if (in_array("Monday", $weekdays)) {
    echo "Workday";
    }
if (in_array("Saturday", $weekdays)) {
    echo "Weekend";
    }

If it is an associative array use array_key_exists

$weekday = array('mon' => 1, 'tue' => 2);
if (array_key_exists('mon', $weekday)) {
    echo "Monday do exists in a week";
}

You can assign manually but you could miss a number so it could lead to an error if you are going through the array values sequentially.

Assignment of values for associative array using the format index => value.

<¿php
$shapes = array('Soda Can' => 'Cylinder',
'Note Pad' => 'Rectangle',
'Apple' => 'Sphere',
'Orange' => 'Sphere',
'Phonebook' => 'Rectangle');
?>

To create associative array from query.

If you want to empty your array, you do this.

unset($myarray);

Continue to Displaying array.

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data