Publications: 120 | Followers: 1

PHP_ Arrays, Strings, and Files - Winthrop

Publish on Category: Birds 0

PHP: Arrays, Strings, and Files
CSCI 297 Scripting Languages - Day Three
Arrays-Numeric Indexes
Remember, you don't need to declare variables.PHP automatically indexes new can access specific locations by using [X].
$animal[] = "aardvark";$animal[] = "bat";$animal[] = "cat";$animal[1] = "bug";$animal[4] = "elephant";print_r($animal);echo "<P>";
Array ( [0] => aardvark [1] => bug [2] => cat [4] => elephant )
Instead of numbers, index is a name.This is very helpful when processing form data that was passed into the script.$name = $_POST['yourname'];
$bosses = array ('president' => "Mahony",'provost' => "Boyd",'dean' =>"Saksena");echo "The Dean is " . $bosses['dean'] . "<P>";
The Dean isSaksena
The "foreach" statement
use "foreach" to loop through an array.
$index = 0;foreach($animal as $nextanimal){echo $index ---- $nextanimal<br>";$index++;}echo "<P>";foreach($bosses as $position => $name)echo "$name is the $position <br>";
0 ---- aardvark1 ---- bug2 ---- cat3 ---- elephantMahonyis the presidentBoyd is the provostSakenaisthe dean
is_array($bosses)returns true or falsecount($animals)returns the array sizesort ($animals)$longstring= "Now is the time for all good men…";$eachword=explode ($longstring);unset ($animals[0])removes aardvarkin_array( 5, $values)is 5 in the array $values?
there are dozens of functions to manipulate stringssee Chapter 4 of textbookmost of the usual C++ functions (strlenandstrcmp) apply in PHP too
// string test$answer =str_repeat("blah ", 3);$answer =strtoupper($answer);echo $answer;
$name =ucwords($name);--- capitalize the first letter of each worducfirst--- capitalize the first letterstrtolower--- lower case all letterssubstr--- copying a substring$string = "Now is the time";echosubstr($string, 1, 5); // "owis"echosubstr($string, -4); // "time"strpos--- search for a substring$location=strpos("Hello World", "H"); // location is0$location=strpos("Hello World","Z"); //location isfalse
Strings- html processing
nl2br($str)-- output a <br> for each \n in $strstripslashes-- remove slash characterstrim-- remove leading and trailing spaces, tabs, newlines, etc.
Files- opening
fopenworks just like C++ondeltona, the server writes your files to the /tmpdirectoryread-write codes:r = read, pointer at startw = write, pointer at starta = write, pointer at endr+ = read and write$fp=fopen("/tmp/dannelly.txt", "w") ordie ("Could not open for writing");fwrite($fp, "Hello World");fclose($fp);
To move around usefseekfseek($fp,0, SEEK_SET); // go to beginningfseek($fp,0, SEEK_END); // go to endfseek($fp,-20,SEEK_CUR); // move back 20 charsTo dump a whole file into an array$filelines= file ("/tmp/myfile.txt");To print a whole fileechofile_get_contents("/tmp/dannelly.txt");more file functions in three weeks





Make amazing presentation for free
PHP_ Arrays, Strings, and Files - Winthrop