Lecture 7& 8
Lecture 7& 8
CS
CS
Arrays
Definition
– To create a sequence of values within a
range
$arrName=range(lower, higher)
$arrName=range(lower, higher, difference)
$days = range(1,7);
$evens = range(2,20,2);
$letters = range(‘a’, ‘z’);
Arrays
Access Array elements
– To access array elements, use index or key
for($i=0;$i<4;$i++)
echo $names[$i];
– We can initialize arrays with keys and associated values
$names = array(‘A’=>’Abebe’,’B’=>’Belay’,
‘F’=>’Fasil’);
– We can create the same array as
$names[‘A’]=“Abebe”;
$names[‘B’]=“Belay”;
$names[‘F’]=“Fasil”;
– To access elements:
echo $names[‘A’];
– Accessing elements using loop:
foreach($names as $myIndex=>$myValue)
echo $myIndex.”=>”.$myValue;
– You can’t use for loop in this case
Arrays
Access Array elements
– each() function returns the next element of an array as an array
with indexes key and value or indexes 0 and 1.
While( $nextElement=each($names)){
echo $nextElement[‘key’].”-”.$nextElement[‘value’];
}
While( $nextElement=each($names)){
echo $nextElement[0].”-”.$nextElement[1];
}
Arrays
Access Array elements
– list() can be used to split an array into a number
of values.
while ( list( $index, $name ) = each( $names ) )
echo $index.” - ”. $name.”<br>”;
– Use reset() to loop through the $names array
again
reset($names);
//loop again here using each() method
Arrays
Multidimensional array
$team=array(array("Abebe","Belay",20),
array("Aster","Fasil",25),
array("Belay","Desta",30));
– To access elements
for ($i=0;$i<3;$i++){
for($j=;$j<3;$j++){
echo $team[$i][$j];
}
echo ”<br>”;
}
Cont.
Arrays
Multidimensional array
– We can also create multidimensional array using keys and values
$team=array( “”array(“fname”=>”Abebe”,
“lname”=>”Belay”, “age”=>20),
array(“fname”=>”Aster”,
“lname”=>”Fasil”, “age”=>25),
array(“fname”=>”Belay”,
“lname”=>”Desta”, “age”=>30));
– To access elements
for($i=0;$i<3;$i++){
while(list($title,$value)=each($team[$i])){
echo $value;
}
}
Arrays
Sorting Arrays
– The function sort() takes one dimensional array and sorts
the elements in ascending order
$names = (“Tesfaye”, “Abebe”, “Kebede”);
Sort($names);
– After this $names contains (“Abebe”, “kebede”,
“Tesfaye”)
– For arrays with key and value combination use
– asort() – to sort based on the values
– ksort() – to sort based on the keys
– To sort in descending order use the functions:
rsort(), krsort(), arsort()
– To sort multidimensional arrays, define a function
Arrays
Reordering arrays
– Shuffle() puts elements in a random order
– array_reverse() returns an array with elements in a reverse order
Navigating within an array
– While using each() function, a pointer points to the next element
– We can redirect this pointer
reset() – takes the pointer to the first element and returns the first element
current() – returns the element at the current pointer position
next() – advances the pointer and returns the current element
prev() – advances the pointer to previous position and returns the element
at that position
end() – takes the pointer to the last position, returns the elem.
Counting elements
– count(array) and sizeof(array) return the number of elements in array
String Manipulation And Regular
Expression
Formatting Strings
Trimming Strings:
trim() - strips whitespace from the start and end of a string
trim(str, ‘listChars’) – strips listChars from end/end str
• Only the end will be cut if both start and end matches listchars
rtrim() – strips whitespace from end of a string
ltrim() – strips whitespace from start of a string
Formatting Strings for printing:
nl2br() – converts newlines (\n) to <br> html tag
print() – same as echo, but it can format a string
$total = 12.4;
printf(“Total = %.2f”, $total); //prints 12.40
Formatting Strings
Change cases:
strtoupper(str) – returns upper case of str
strtolower(str) – returns lower case of str
ucfirst(str) – returns str with first letter in
upper case
ucwords() – returns str with first letter in each word in
upper case
Formatting Strings for Storage – store in DB:
addslashes() – adds escape character (\)
stripslashes() – removes escape character
• magic_quotes_gpc - is configured to add/remove slashes
automatically
Formatting Strings
Joining and Splitting Strings:
explode(separator, str) – returns an array of strings by breaking
str using separator
• $address=explode(‘@’, [email protected])
returns an array containing “info” and “bdu.edu.et”
implode() – does the opposite of explode(), joins elements of an
array using a string glue
• Implode(“@”, $address) returns [email protected]
join() – same as implode()
stroke() – returns a single fragment of the string using the
separator.
• Can take multiple separators
$token = stroke($str, “ .,;”);
while($token!=“ “){
echo$token;
$token = stroke($str, “ .,;”);
}
Formatting Strings
Joining and Splitting Strings:
string substr(string str, int start , int length ) – returns a
substring starting from start index to the last or the
given length.
Comparing Strings:
int strcmp(string str1, string str2) – returns: 0 if they are
equal, 1 if str1 is greater than str2, less than 0 if str1
less than str2
• It is case sensitive
strcasecmp() – identical to strcmp() but it is not case
sensitive
Formatting Strings
Testing String Length:
int strlen(string str) – takes a string and returns the
number of characters
Finding Strings in Strings:
string strstr(string haystack, string needle) - If an exact
match of the needle is found, the function returns
the haystack from the needle onward; otherwise, it
returns false
• If the needle occurs more than once, the returned string will start
from the first occurrence of needle.
stristr() - identical but is not case sensitive
strrchr() – which is again nearly identical, but returns
the haystack from the last occurrence of the needle
onward.
Formatting Strings
Finding the Position of a Substring:
int strpos(string haystack, string needle, int
[offset] ) – returns the position of the first
occurrence of the needle within haystack
• Starts searching at offset
$test = ‘Hello world’;
strpos($test, ‘o’); - returns 4
strpos($test, ‘o’, 5); - returns 7