350 likes | 554 Views
Arrays In PHP. By: Junejo Naeem Ahmed. Arrays. Arrays are complex variables that store a group of values under a single variable name. An array is useful for storing a group of related values. Creating and Working with Arrays.
E N D
Arrays In PHP By: JunejoNaeem Ahmed
Arrays • Arrays are complex variables that store a group of values under a single variable name. • An array is useful for storing a group of related values.
Creating and Working with Arrays • To create a variable, you assign a value to it. Similarly, the simplest way to create an array is to assign a value to it. • $customers[ 1 ] = “Ali”; • At this point, the array named $customers has been created and holds only one value — Ali. • Next, you use the following statements: • $customers[ 2 ] = “Ahmed”; • $customers[ 3 ] = “Hassan”; • Now, the array $customers contains three values: Ali , Ahmed, and Hassan.
Creating and Working with Arrays … • An array can be viewed as a list of key/value pairs, stored as follows: • $arrayname[‘key1’] = value1; • $arrayname[‘key2’] = value2; • $arrayname[‘key3’] = value3; • and so on up to any number of elements in the array. • The key is also referred to as the index.
Creating and Working with Arrays … • Arrays can use either numbers or strings for keys. In the $customers array, the keys are numbers — 1, 2, and 3. • However, you can also use strings for keys. • For example, the following statements create an array of state capitals: • $capitals[‘Sindh’] = “Karachi”; • $capitals[‘Punjab’] = “Lahore”; • $capitals[‘Baluchistan’] = “Quetta”;
Creating and Working with Arrays … • Or you can use shortcuts to create arrays, rather than write separate assignment statements for each number. • One shortcut uses the following statements: • $customers[] = “Ali”; • $customers[] = “Ahmed”; • $customers[] = “Hassan”; • When you create an array by using this shortcut, the values are automatically assigned keys that are serial numbers, starting with the number 0.
Creating and Working with Arrays … • An even shorter shortcut is to use the following statement: • $customers = array ( “Ali”,”Ahmed”,”Hassan”); • $ customers = array ( 1 => “Ali”,” Ahmed”,” Hassan”); • You can also create an array with a range of values by using the following statement. • $years = range(2001, 2010);
Viewing arrays • You can see the structure and values of any array by using one of two statements — var_dump or print_r. • The print_r() statement, however,gives somewhat less information. • To display the $customers array, use the following statement: • print_r($customers); • To get more information, use the following statement. • var_dump($customers);
Modifying arrays • 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;
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]);
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);
Finding Array Size • You can find out the size of your array by using either the count statement or a sizeof statement. • The format for these statements is as follows • $n = count($arrayname); • $n = sizeof($arrayname); • After either of these statements, $n will contain the number of elements in the array.
Using Arrays in Statements • Arrays can be used in statements in the same way that variables are used in. • You can retrieve any individual value in an array by accessing it directly, as in the following example: • $Sindhcapital = $capitals[‘Sindh’]; • echo $Sindhcapital;
Using arrays in echo statements • You can echo an array value like this: • echo = $capitals[‘Sindh’];
Using arrays in list statements • You can retrieve several values at once from an array with the list statement. • The list statement copies values from an array into variables. • $colors=array(“red”,”green”); • List($red,$green)=$colors;
Retrieve the key from an array • In some cases, you may want to retrieve the key from an array element rather than the value. • Suppose the following element is the first element in an array: • $capitals[‘Sindh’] = “Karachi”; • $value = $capitals[‘Sindh’]; • $key = key($capitals); • echo “$key: $value”;
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.
Traversing an array manually • current($arrayname): Refers to the value currently under the pointer. • next($arrayname): Moves the pointer to the value after the current value. • previous($arrayname): Moves the pointer to the value before the current pointer location. • end($arrayname): Moves the pointer to the last value in the array. • reset($arrayname): Moves the pointer to the first value in the array.
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 ( $arraynameas $keyname=> $valuename) • { • block of statements; • }
Converting Arrays into Strings (And Vice Versa) • You can create an array that contains the contents of a string by using a statement in the following format: • $arrayname = explode(“s”,string); • Conversely, you can convert an array into a string by using the following statement: • $resString = implode(“s”,$array);
Splitting Arrays • You can split an array by creating a new array that contains a subset of an existing array. • You can do this by using a statement of the following general format: • $subArray = array_slice($arrayname,n1,n2);
Merging Arrays • Conversely, you can merge two or more arrays together by using the following statement: • $bigArray = array_merge($array1,$array2,...);
Summing arrays • To add all the values in an array, use the following statement: • $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.
Removing duplicate items • $names2 = array_unique($names);
Exchanging keys and values • To exchange the values, use the following statement: • $arrayFlipped = array_flip($testarray);
Multidimensional Arrays • I describe arrays that are a single list of key/value pairs. • However, on some occasions, you may want to store values with more than one key.
Creating multidimensional arrays • You can create multidimensional arrays in the same ways you create one dimensional arrays. • $foodPrices[‘vegetable’][‘potato’] = 1.00; • $foodPrices[‘fruit’][‘apple’] = 2.50; • You can also use a shortcut and allow PHP to choose the keys, as follows: • $foodPrices[‘vegetable’][ ] = 1.00; • $foodPrices[‘fruit’][ ]= 2.50;
Viewing multidimensional arrays • You can view a multidimensional array in the same ways you can view any array — by using the print_r or the var_dump statements.
Using multidimensional arrays in statements • You can get values from a multidimensional array by using the same procedures that you use with a one-dimensional array. • you can access a value directly with this statement: • $hamPrice = $foodPrices[‘vegetable’][‘potato’] • You can also echo the value: • echo $foodPrices[‘vegetable’][‘potato’]
Sorting Arrays • One of the most useful features of arrays is that PHP can sort them for you. • PHP originally stores array elements in the order in which you create them. • PHP can sort arrays in a variety of ways. • To sort an array that has numbersas keys, use a sort statement as follows: • sort($arrayname); • This statement sorts arrays by the values and assigns new keys that are the appropriate numbers. • The values are sorted with numbers first, uppercase • letters next, and lowercase letters last.
Sorting Arrays • If you use sort() to sort an array with words as keys, the keys are changed to numbers, and the word keys are thrown away. • To sort arrays that have words for keys, use the asort statement as follows: • asort($capitals);
Ways You Can Sort Arrays • sort($arrayname) Sorts by value; assigns new numbers as the keys. • asort($arrayname) Sorts by value; keeps the same key. • rsort($arrayname) Sorts by value in reverse order; assigns new numbers as the keys. • arsort($arrayname) Sorts by value in reverse order; keeps the same key. • ksort($arrayname) Sorts by key. • krsort($arrayname) Sorts by key in reverse order.
Assigments Make a page having one textbox if a user enter value suppose 2 than on next page make dynamic 2 fieldsets having username,Address and Gender contact, nic and while entering in contact textbox here user is capable of entering more than 1 contacts seperated each contact through comma on submit these values should be stored in array and shown on third page.
Assigments • Take an unsorted array and sort it using bubble sort technique. • Make an array which should contain intersected values of two given arrays. • Take an input of NICs of students applying for two different departments of an educational institute, there should be a form to collect the data of students. After submitting the form, we should be able to Detect those students who applied in more then one departments.