Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Arrays and Strings in PHP: Declaration, Use, and Functions - Prof. David L. Tarnoff, Study notes of Computer Science

A part of the csci 2910 client/server-side programming course materials. It covers the declaration, use, and functions of arrays and strings in php. Topics include variable scope, static variables, creating and printing arrays, alternate indices, strings as array indices, array functions such as count(), array_fill(), range(), in_array(), array_search(), and more. String functions like explode(), printf(), strtolower(), strtoupper(), ucfirst(), and various substring functions are also discussed.

Typology: Study notes

Pre 2010

Uploaded on 08/18/2009

koofers-user-50p-1
koofers-user-50p-1 🇺🇸

10 documents

1 / 8

Toggle sidebar

Related documents


Partial preview of the text

Download Arrays and Strings in PHP: Declaration, Use, and Functions - Prof. David L. Tarnoff and more Study notes Computer Science in PDF only on Docsity! 1 Arrays and Strings – Page 1 of 48CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: Arrays and Strings in PHP Reading: Williams & Lane pp. 57–87 Arrays and Strings – Page 2 of 48CSCI 2910 – Client/Server-Side Programming Today’s Goals Today’s lecture will cover: • Arrays – declaration and use • Array functions • String functions Arrays and Strings – Page 3 of 48CSCI 2910 – Client/Server-Side Programming Variable Scope • Variables declared within a function are typically visible only within the function • PHP doesn't give an error when an undeclared variable is being used – it just initializes it to null. • You will not get an error when using variables that are out of scope, only a null value returned. • Can resolve this by taking advantage of passing parameters to functions and returning a value from a function. Arrays and Strings – Page 4 of 48CSCI 2910 – Client/Server-Side Programming Variable Scope (continued) • For example, the following code will output "The value is " function myfunc() { $ival = 25; } myfunc(); print "The value is ".$ival; Arrays and Strings – Page 5 of 48CSCI 2910 – Client/Server-Side Programming Global Variables • Variables can be made global with the global keyword. • For example, the following code will output "The value is 25" function myfunc() { global $ival; $ival = 25; } myfunc(); print "The value is ".$ival; Arrays and Strings – Page 6 of 48CSCI 2910 – Client/Server-Side Programming Static Variables • Static variables are not visible outside of the function, but the last value stored in a static variable will be available the next time the function is called. • They are declared using the static keyword. • They must be initialized in the same line where they are declared or they will be reinitialized with each subsequent execution of the function. 2 Arrays and Strings – Page 7 of 48CSCI 2910 – Client/Server-Side Programming Static Variables (continued) • The following code: function myfunc() { static $ival=0; // Initial value $ival++; return($ival); } print "The value is ".myfunc()."<br />"; print "The value is ".myfunc()."<br />"; • has the following output: The value is 1 The value is 2 Arrays and Strings – Page 8 of 48CSCI 2910 – Client/Server-Side Programming Arrays in PHP • Arrays in PHP are much like arrays in JavaScript except that they include some additional "features" • As with JavaScript, each object within the array is referenced using an index. • The elements of an array act just like variables in that you can modify them or use them to define other elements. • Unless otherwise specified, PHP assigns the first object in the list the index/key 0. • To use the array's index to point to a specific element, use the square brackets [ and ]. Arrays and Strings – Page 9 of 48CSCI 2910 – Client/Server-Side Programming Creating Arrays in PHP • Declared using array keyword • Initialized using list of items in parenthesis after array keyword • Examples: $names = array("Bob", "Larry", "Mr. Lunt"); $numbers = array(345, 4562, 72, 1, 657); • Arrays may contain mixed data types. This will help us when retrieving a record from MySQL. • Example: $mixed = array(5.2, "apple", true, 42); Arrays and Strings – Page 10 of 48CSCI 2910 – Client/Server-Side Programming Creating Arrays in PHP (continued) • Array elements can also be created by assigning values to new, unset indices/keys. • Example: $names[3] = "Archibald"; • If no index is specified, the value is assigned to the next available index. • Example: $names[] = "Jimmy"; Arrays and Strings – Page 11 of 48CSCI 2910 – Client/Server-Side Programming Printing Arrays • Individual elements from an array can be printed simply by referencing their index. print $names[2]; // Should print "Mr. Lunt" • When printing arrays as part of a string, the curly brackets should be used. Take for instance the PHP code: print "Array element 2 is $names[2]."; • Some PHP engines would output: Array element 2 is Array[2]. • To fix this, use the curly brackets: print "Array element 2 is {$names[2]}."; Arrays and Strings – Page 12 of 48CSCI 2910 – Client/Server-Side Programming Printing Arrays (continued) • To debug an array, you can also print out the entire array using the print_r() function. • Example: print_r($names); • Output from previous code: Array ( [0] => Bob [1] => Larry [2] => Mr. Lunt [3] => Archibald [4] => Jimmy ) • You must use parenthesis with print_r() as it is a function. 5 Arrays and Strings – Page 25 of 48CSCI 2910 – Client/Server-Side Programming count() • The function count() returns the number of elements in an array. • The code: $names = array("Bob", "Larry", "Mr. Lunt"); print "Number of elements = ".count($names); outputs: Number of elements = 3 Arrays and Strings – Page 26 of 48CSCI 2910 – Client/Server-Side Programming array_fill() • The function array_fill() creates and returns an array filled with a designated value. • Syntax: array_name = array_fill(integer start, integer count, mixed fill_value) • The code: $new_array = array_fill(2, 4, "a"); print_r ($new_array); outputs: Array ( [2] => a [3] => a [4] => a [5] => a ) Arrays and Strings – Page 27 of 48CSCI 2910 – Client/Server-Side Programming range() • The function range() creates and returns an array filled with a sequence of values starting with a value low and ending at a value high with an optional step. (Our server doesn't appear to like step.) • Syntax: array_name = range(mixed low, mixed high[, integer step]) • The code: $new_array = range("a", "e"); print_r ($new_array); outputs: Array ( [0] => a [1] => b [2] => c [3] => d [4] => e ) Arrays and Strings – Page 28 of 48CSCI 2910 – Client/Server-Side Programming max() and min() • The functions max() and min() can be used to return the maximum and minimum elements of an array. The elements must be numbers • Syntax: number max(array_of_numbers) number min(array_of_numbers) • The code: $numbers = array(345, 4562, -72, 1, 657); print "Maximum = ".max($numbers)."\n"; print "Minimum = ".min($numbers); outputs: Maximum = 4562 Minimum = -72 Arrays and Strings – Page 29 of 48CSCI 2910 – Client/Server-Side Programming in_array() • To simplify the process of checking an array for a specific element, PHP offers the in_array() function. • in_array() returns a boolean true if it finds the element in the array. • Syntax: boolean in_array(mixed element, arrayname) • The following would print "betsy is a valid user." $username = "betsy"; $users = array("adam", "betsy", "carl"); if(in_array($username, $users)) print $username." is a valid user."; Arrays and Strings – Page 30 of 48CSCI 2910 – Client/Server-Side Programming array_search() • The problem with in_array() is that frequently, you want the index returned if it is in the array. • array_search() returns the array index instead of a boolean true if value is found and a false if the value is not found. • By the way, since a false can act like a 0 which would be the typical index of the first element, use the is-identical to operator "===". This will force the type to match in addition to value. • The following code would output "2". $users = array("adam", "betsy", "carl"); print array_search("carl", $users); 6 Arrays and Strings – Page 31 of 48CSCI 2910 – Client/Server-Side Programming More Array Functions • array_key_exists() – returns true if an element with a specific index/key exists. Returns false otherwise. • array_merge() – returns an array which is the result of combining 2 or more arrays • array_reverse() – reverses the order of the elements in an array. It can also be told to preserve the indices/keys which would result in the indices/keys also be reversed. Arrays and Strings – Page 32 of 48CSCI 2910 – Client/Server-Side Programming Array Element Sorting Functions • sort() – rearranges array elements in ascending order • rsort() – rearranges array elements in descending order • asort() – rearranges array elements in ascending order keeping keys associated with elements • arsort() – rearranges array elements in descending order keeping keys associated with elements • ksort() – rearranges array elements in ascending order of keys • krsort() – rearranges array elements in descending order of keys Arrays and Strings – Page 33 of 48CSCI 2910 – Client/Server-Side Programming String Functions • Strings have plenty of functions in PHP too. (Almost 100 according to http://www.php.net/manual/en/ref.strings.php) • Mercifully, we will not be responsible for them all. Arrays and Strings – Page 34 of 48CSCI 2910 – Client/Server-Side Programming join() or implode() • join() and implode() are the same function. • This function takes an array of elements and turns it into one long string. • The separator is placed between each array element • Syntax: string join(string delimiter, arrayname) • The code: $words = array("The", "dog", "chased", "the", "ball."); $sentence = join(" ", $words); print $sentence; will produce the string "The dog chased the ball." Arrays and Strings – Page 35 of 48CSCI 2910 – Client/Server-Side Programming explode() • Syntax: array explode ( string separator, string string [, int limit] ) • explode() returns an array of strings, each of which is a substring of string of the original string divided at the string separator. • If limit is used, the maximum number of elements will be set to limit, the last element of which will contain the rest of string. • The code $words = explode(".", "423.439.6404"); print_r ($words); • outputs "Array ( [0] => 423 [1] => 439 [2] => 6404 )" Arrays and Strings – Page 36 of 48CSCI 2910 – Client/Server-Side Programming strlen() • strlen() returns the length of the string in characters. • Syntax: integer strlen(string) • The code: print strlen("The quick brown fox jumps over the lazy dog."); outputs "44". 7 Arrays and Strings – Page 37 of 48CSCI 2910 – Client/Server-Side Programming Formatted Output • When using print, the programmer is at the mercy of the PHP engine in terms of how elements such as variables will be output. • For example, print M_PI; will output "3.1415926535898" • printf() gives formatting control to the programmer. • Syntax: printf(string_w_formatting, arguments) • Specifiers located within the "string_w_formatting" identify where the arguments are to be placed and the format they are to follow. • Multiple arguments are separated with commas. Arrays and Strings – Page 38 of 48CSCI 2910 – Client/Server-Side Programming Specifiers String%s Float w/specific decimal point placement%f Hexadecimal integer%x Octal integer%o Unsigned decimal integer%u Signed decimal integer%d ASCII character%c Binary integer%b "Escape" sequence to print '%'%% DescriptionSpecifier Arrays and Strings – Page 39 of 48CSCI 2910 – Client/Server-Side Programming printf() Examples • Code: printf ("Pi = %5.3f", M_PI); Output: "Pi = 3.142" • Code: printf ("%d in binary is %b", 25, 25); Output: "25 in binary is 11001" • Code: printf ("The ASCII value of %c is %x hex", 72, 72); Output: "The ASCII value of H is 48 hex" • Code: printf("%s owns %d computers", "Tom", 5); Output: "Tom owns 5 computers" Arrays and Strings – Page 40 of 48CSCI 2910 – Client/Server-Side Programming Modifying Case • strtolower() – returns a copy of the string argument in all lower case • strtoupper() – returns a copy of the string argument in all upper case • ucfirst() – returns a copy of the string argument with the first character in upper case. Doesn't affect rest of string, therefore to verify sentence case, use strtolower() first. • ucwords() – returns a copy of the string argument with the first character of each word in upper case. Doesn't affect rest of string, therefore to verify title case, use strtolower() first. Arrays and Strings – Page 41 of 48CSCI 2910 – Client/Server-Side Programming Trimming Whitespace • There are three functions used to trim leading and/or trailing whitespace • Whitespace includes spaces, tabs, newlines, and carriage returns – trim(string[, character list]) – returns string with leading and trailing whitespace removed – rtrim(string[, character list]) – returns string with trailing (right) whitespace removed – ltrim(string[, character list]) – returns string with leading (left) whitespace removed • string is the string to be modified • character list allows the programmer to specify a string of the exact characters to trim • A range of characters is represented with ".." Arrays and Strings – Page 42 of 48CSCI 2910 – Client/Server-Side Programming Examples of Trimming Whitespace • print trim(" 302 Just an example..."); outputs "302 Just an example…" • print trim(" 302 Just an example...", "0..9."); outputs " 302 Just an example" • print trim(" 302 Just an example...", "0..9. "); outputs "Just an example"
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved