php array 1

28
WORKING WITH ARRAYS

Upload: syed-mudasir-shah

Post on 16-Jul-2015

68 views

Category:

Education


0 download

TRANSCRIPT

Page 1: PHP array 1

WORKING WITH ARRAYS

Page 2: PHP array 1

ARRYAS

• Array is a data structure, which provides the facility to store a collection of data of same type under single variable name.

• An array is a collection of data values, organized as an ordered collection of key-value pairs.

Page 3: PHP array 1

INDEXED VERSUS ASSOCIATIVE ARRAYS• There are two kinds of arrays in PHP:• indexed and associative.• The keys of an indexed array are integers,

beginning at 0.• Indexed arrays are used when you identify things

by their position.• Associative arrays have strings as keys and behave

more like two-column tables.• The first column is the key, which is used to access

the value.

Page 4: PHP array 1

INDEXED VERSUS ASSOCIATIVE ARRAYS• In both cases, the keys are unique--that is, you

can't have two elements with the same key, regardless of whether the key is a string or an integer.

• PHP arrays have an internal order to their elements that is independent of the keys and values, and there are functions that you can use to traverse the arrays based on this internal order.

• The order is normally that in which values were inserted into the array.

Page 5: PHP array 1

IDENTIFYING ELEMENTS OF AN ARRAY• You can access specific values from an array using the array

variable's name,

• followed by the element's key (sometimes called the index) within square brackets:

• $age['Fred']

• $shows[2]

• The key can be either a string or an integer.

• String values that are equivalent to integer numbers (without leading zeros) are treated as integers.

• Thus, $array[3] and $array['3'] reference the same element, but $array['03'] references a different element.

Page 6: PHP array 1

IDENTIFYING ELEMENTS OF AN ARRAY

• You don't have to quote single-word strings.

• For instance,

• $age['Fred'] is the same as $age[Fred].

• However, it's considered good PHP style to always use quotes, because quoteless keys are indistinguishable from constants.

Page 7: PHP array 1

STORING DATA IN ARRAYS

• Storing a value in an array will create the array if it didn't already exist.

• For example:

• echo $addresses[0]; // prints nothing

• echo $addresses; // prints nothing

• $addresses[0] = '[email protected]';

• echo $addresses; // prints "Array"

• $addresses[0] = '[email protected]';

• $addresses[1] = '[email protected]';

• $addresses[2] = '[email protected]';

Page 8: PHP array 1

STORING DATA IN ARRAYS

• $price[ 'Gasket‘ ] = 15.29;

• $price[ 'Wheel‘ ] = 75.25;

• $price[ 'Tire‘ ] = 50.00;

• An easier way to initialize an array is to use the array( ) construct, which builds an array from its arguments:

• $addresses = array( '[email protected]', '[email protected]', '[email protected]‘ );

Page 9: PHP array 1

STORING DATA IN ARRAYS

• To create an associative array with array( ),

• use the => symbol to separate indexes from values:

• $price = array( 'Gasket' => 15.29,

• 'Wheel' => 75.25,

• 'Tire' => 50.00);

• $price = array( 'Gasket'=>15.29,'Wheel'=>75.25,'Tire'=>50.00);

• To construct an empty array, pass no arguments to array( ):

• $addresses = array( );

Page 10: PHP array 1

STORING DATA IN ARRAYS

• You can specify an initial key with => and then a list of values.

• The values are inserted into the array starting with that key, with subsequent values having sequential keys:

• $days = array(1 => 'Monday', 'Tuesday', 'Wednesday',

• 'Thursday', 'Friday', 'Saturday', 'Sunday');

• // 2 is Tuesday, 3 is Wednesday, etc.

• If the initial index is a non-numeric string, subsequent indexes are integers beginning at 0.

• $whoops = array('Friday' => 'Black', 'Brown', 'Green');

• // same as

• $whoops = array('Friday' => 'Black', 0 => 'Brown', 1 => 'Green');

Page 11: PHP array 1

ADDING VALUES TO THE END OF AN ARRAY

• To insert more values into the end of an existing indexed array, use the [] syntax:

• $family = array('Fred', 'Wilma');

• $family[] = 'Pebbles'; // $family[2] is 'Pebbles'

• This construct assumes the array's indexes are numbers and assigns elements into the next available numeric index, starting from 0.

• Attempting to append to an associative array is almost always a programmer mistake, but PHP will give the new elements numeric indexes without issuing a warning:

• $person = array('name' => 'Fred');

• $person[] = 'Wilma'; // $person[0] is now 'Wilma'

Page 12: PHP array 1

VIEWING ARRAYS

• You can see the structure and values of any array by using one of two functions — var_dump or print_r.

• The print_r() statement, however, gives somewhat less information.

• To display the $customers array, use the following functions: print_r($customers);

• To get more information, use the following functions: var_dump($customers);

Page 13: PHP array 1

MODIFYING ARRAY & STORING ONE ARRAY IN ANOTHER

• Arrays can be changed at any time in the script, just as variables can.

• The individual values can be changed, elements can be added or removed, and elements can be rearranged.

• $customers[2] = “John”;

• $customers[4] = “Hidaya”;

• $customers[] = “Dell”;

• You can also copy an entire existing array into a new array with this statement:

• $customerCopy = $customers;

Page 14: PHP array 1

REMOVING VALUES FROM ARRAYS

• Sometimes you need to completely remove a value from an array.

• $colors = array ( “red”, “green”, “blue”, “pink”, “yellow” );

• $colors[ 3 ] = “”;

• Although this statement sets $colors[3] to blank, it does not remove it from the array. You still have an array with five values, one of the values being an empty string.

• To totally remove the item from the array, you need to unset it.

• unset($colors[3]);

Page 15: PHP array 1

REMOVING VALUES FROM ARRAYS

• Removing all the values doesn’t remove the array itself

• To remove the array itself, you can use the following statement

• unset($colors);

Page 16: PHP array 1

USING ARRAYS IN STATEMENTS

• Arrays can be used in statements in the sameway that variables are used in.

• You can retrieve any individual value in anarray by accessing it directly, as in thefollowing example:

• $Sindhcapital = $capitals[‘Sindh’];

• echo $Sindhcapital;

• You can echo an array value like this:

• echo $capitals[‘Sindh’];

Page 17: PHP array 1

GETTING THE SIZE OF AN ARRAY

• The count( ) and sizeof( ) functions are identical in use and effect.

• They return the number of elements in the array.

• Here's an example:

• $family = array('Fred', 'Wilma', 'Pebbles');

• $size = count($family); // $size is 3

• These functions do not consult any numeric indexes that might be present:

• $confusion = array( 10 => 'ten', 11 => 'eleven', 12 => 'twelve');

• $size = count($confusion); // $size is 3

Page 18: PHP array 1

WALKING THROUGH AN ARRAY

• Walking through each and every element in an array, in order, is called iteration.

• It is also sometimes called traversing.• Two ways to walk through an array:• Traversing an array manually:

– Uses a pointer to move from one array value to another.

• Using foreach:– Automatically walks through the array, from beginning to

end, one value at a time.

Page 19: PHP array 1

USING FOREACH TO WALK THROUGH AN ARRAY

• You can use foreach to walk through an array one value at a time and execute a block of statements by using each value in the array.

• The general format is as follows:foreach ( $arrayname as $keyname => $valuename ){

block of statements;}

Page 20: PHP array 1

RANGE()

• You can also create an array with a range of values by using the following function.

$years = range(2001, 2010,[step]);

• Here step is a positive number which has default value 1. Step is used for number of increment.

Page 21: PHP array 1

LIST()

• You can retrieve several values at once from an array with the list function.

• The list function copies values from an array into variables.•

$colors=array(“red”,”green”);list($red,$green)=$colors;

Page 22: PHP array 1

ARRAY_SLICE()

• You can split an array by creating a new array that contains a subset of an existing array.

• Works same as substr works for string.• You can do this by using following function:

$subArray = array_slice($arrayname,start,length);

Page 23: PHP array 1

ARRAY_MERGE()

• Conversely, you can merge two or more arrays together by using the following function:

$bigArray = array_merge($array1,$array2,...);

Page 24: PHP array 1

ARRAY_SUM()

• To add all the values in an array, use the following function:• $sum = array_sum($array);

• Of course, you are only going to add elements in an array of numbers.

• PHP converts strings to 0 if you try to add them.

Page 25: PHP array 1

ARRAY_UNIQUE()

• Removes duplicate items from an array:

$names2 = array_unique($names);

Page 26: PHP array 1

ARRAY_FLIP()

• To swap the keys and values, use the following function:

$arrayFlipped = array_flip($testarray);

Page 27: PHP array 1

extract()

• Extracts array, forms variables with the names of keys or indexes of array.

• extract($array);

Page 28: PHP array 1

ASSIGMENTS

1. Make a linear Search using array.2. Take an unsorted array and sort it using bubble sort

technique.3. Make an array which should contain intersected values of

two given arrays.