+ All Categories
Home > Documents > » PHP arrays are lists of values stored in key-value pairs. » Uses of arrays: Many built-in PHP...

» PHP arrays are lists of values stored in key-value pairs. » Uses of arrays: Many built-in PHP...

Date post: 26-Mar-2015
Category:
Upload: mason-gonzalez
View: 272 times
Download: 3 times
Share this document with a friend
Popular Tags:
7
Transcript
Page 1: » PHP arrays are lists of values stored in key-value pairs. » Uses of arrays: Many built-in PHP environment variables. Database functions use arrays.
Page 2: » PHP arrays are lists of values stored in key-value pairs. » Uses of arrays: Many built-in PHP environment variables. Database functions use arrays.

» PHP arrays are “lists” of values stored in key-value pairs.

» Uses of arrays:• Many built-in PHP environment variables.• Database functions use arrays.• Entire form arguments in one array.• Nice container for sorting and counting

Page 3: » PHP arrays are lists of values stored in key-value pairs. » Uses of arrays: Many built-in PHP environment variables. Database functions use arrays.

$array[index] = value;

$state_location[‘San Diego’] = ‘CA’;$state = $state_location[‘San Diego’];

$my_array[1] = ‘First Thing’;$my_array[2] = ‘Second Thing’;

$vegetables[] = ‘carrot’;$vegetables[] = ‘lettuce’;

$fruits = array(‘red’ => ‘apple’, ‘green’ => ‘pear’ );

echo $fruits[‘red’]; // prints apple

Page 4: » PHP arrays are lists of values stored in key-value pairs. » Uses of arrays: Many built-in PHP environment variables. Database functions use arrays.

» is_array($variable)• Returns true if variable is an array

» count($array)• Returns number of non-empty elements

» in_array(value, $array)• Returns true if value found in array

» isset($array[key])• Returns true if key is valid for the array

» unset($array[key])• Deletes a key value pair from the array

Page 5: » PHP arrays are lists of values stored in key-value pairs. » Uses of arrays: Many built-in PHP environment variables. Database functions use arrays.

» To execute commands on each item in an array, use the foreach loop

» Foreach runs as many times as there are key/values in an array

» Reference:php.net - foreach

Page 6: » PHP arrays are lists of values stored in key-value pairs. » Uses of arrays: Many built-in PHP environment variables. Database functions use arrays.

$my_array[1] = ‘First Thing’;$my_array[2] = ‘Second Thing’;

foreach($my_array as $value){echo $valueecho '<br />';

}

OUTPUT:

First ThingSecond Thing

Page 7: » PHP arrays are lists of values stored in key-value pairs. » Uses of arrays: Many built-in PHP environment variables. Database functions use arrays.

» Now it’s your turn.

1. We will use the foreach loop to delete one or many comments from the admin_comments page

2. Save the files in the Blog folder.3. Confirm the pages work in a browser.4. Revel in your programming glory.


Recommended