Metropolitan State University

ICS 325

Internet Application Development

 

Class Notes – Chapter 2&3 – Using Files and Arrays

 

There are two ways to save data in PHP; using a database and using flat files.

A flat file is simply a text file.

 

File processing basics

The basic steps in file processing are:

Reading:        Open the file.                         // Handle errors properly if missing or corrupt

                        Read data from file.

                        Close the file.

Writing            Open the file.                         // Create file if missing, and handle any error

                        Write data to the file.

                        Close the file.

 

Opening the file

The most common function for opening files in PHP is fopen().

 

fopen (string fileName, string fileMode [, int use_include_path])

 

fileName = a string value that specifies where the file is located.

fileMode = How the file will be opened.

use_include_path = look for the file in the include path if not found.

File Modes for fopen()

 

Mode

Description

r

Access the file for reading only, start access from beginning of the file.

r+

Access the file for both reading and writing, start access from beginning of the file.

w

Access the file for writing only, If the file exists, erase all contents. If file does not exist, an attempt will be made to create the file. In either case access the file from the beginning.

w+

Access the file for both reading and writing, If the file exists erase all contents. If the file does not exist, an attempt will be made to create the file. In either case, access the file from the beginning.

a

Open the file for writing only. If the file does not exist, an attempt will be made to create it. If the file does exist, access will start from the end of the file (no erasing).

a+

Open the file for reading and writing. If the file does not exist, an attempt will be made to create it. If the file does exist, access will start from the end of the file (no erasing).

 

Reading Data from a file

One of the basic file input functions in PHP is fgets()

fgets (int filePointer [,int length])

            filePointer = a reference to the opened file

length [optional] = the length of data that will be read from the file line.  If this line is omitted by default 1024 bytes are used.  The file will be read until the passed in length, or default value, is met; an end of file is met; or a new line is met.

 

End of the File

            feof (int filePointer) returns a true value when the end of the file is reached.

            filePointer = a reference to the opened file

 

Writing Data to a file

One of the basic file output functions in PHP is fputs()

fputs (int filePointer, string outputString [,int length])

            filePointer = a reference to the opened file.

            outputString = the string that will be written to file.

length [optional] = the length of data that will be written the file line.

 

            NOTE:           File permissions must be set to write to files. 

If the file does not exist, chmod a+w for the directory.

If the file does exist, chmod a+w for the file.

 

Closing the file

The most common function for closing files in PHP is fclose().

            fclose (int filePointer)

filePointer = the reference to the file that was opened.

 

Example:

            <?php

              $filePointer = fopen (“/tmp/myFile.txt”,”w+”);

              echo “Line 1: ”fgets ($filePointer);

              $newText = “Add this line to the file”;

              fputs ($filePointer, $newText);

              fclose ($filePointer);

            ?>

 

Problems with Flat Files

Large files are slow

Searching is difficult

Concurrent access is not reliable

Random access is not available

Cannot set different levels of access to different parts of the data

 

What is the answer to file IO?

 

RDBMS

 

 

Arrays

 

An array is a multi-valued variable

An array stores one of more values, each is identified by an index.
            Array Notation
                        $   arrayName   [index]

Array Declaration

                        $myArray = array(12345, 23456, 34567, 45678);

Array Value Assignment
                        $myArray[0] = 12345;
            Array Value Retrieval
                        $myVar = $myArray[0];                    

                       

                       

Associative Arrays

 

An alternative to numerically based arrays.
An Associative Array defines its own indexes, or keys.
Associative Array Declaration

                        $myArray = array ( “number1”=>12345, ”number2”=>23456, ”number3”=>34567);

Associative Array Value Assignment
                        $myArray[“number1”] = 12345;
            Associative Array Value Retrieval
                        $myVar = $myArray[number1];                   

 

Multidimensional Arrays

An array can store more than simple variables,    arrays can store other arrays.
            An array of arrays is a multidimensional array.

Multidimensional Array Declaration

                        $myArray =    array  (array(123,456,789)

array(134,468,824)

array(321,654,987));

Multidimensional Array Value Assignment
            $myArray[0,0] = 123;
Multidimensional       Array Value Retrieval
            $myVar = $myArray[1,1];                

 

           


Multidimensional Associative Array Example:

<?php

     $cpu = array(

          "AMD"=>array("price"=>"125.00","speed"=>"1.6 GHz","type"=>"Athlon XP"),

          "INT"=>array("price"=>"135.00","speed"=>"1.7 GHz","type"=>"Pentium 4")

     );

     echo "An AMD ".$cpu['AMD']['type']." ";

echo $cpu['AMD']['speed']." costs $";

echo $cpu['AMD']['price'];

     echo "<br />";

     echo "An Intel".$cpu['INT']['type']." ";

echo $cpu['INt']['speed']." costs $";

echo $cpu['INT']['price'];

?>



Output =

An AMD Athlon XP 1.6 GHz costs $125.00
An Intel Pentium 4 1.7 GHz costs $135.00

 

Looping through Arrays

For scalar arrays and multidimensional arrays any standard counting schemes with any loop will suffice.

For associative arrays, each() and list() are available.

The function each() splits values out from an associative array

$element = each ($arrayName)

$element[“key”]

$element[“value”]

The function list () allows the developer to define the variables that the function each () splits into.

List ($myVar1, $myVar2) = each ($arrayName)

$myVar1

$myVar2

 

The functions each () & list () can be used with a while loop to traverse an associative array

           

Sorting Arrays

sort ()              normal array sorting

            assort ()          associative array sorting on values

            ksort ()            associative array sorting on keys

            rsort ()             normal array sorting in reverse order

            krsort ()           associative array sorting on keys in reverse order

            arsort ()           associative array sorting on values in reverse order

            usort ()            user defined sort, function accepts the array and a sorting function

usort ()            user defined sort for associative arrays, function accepts the array and a sorting function

 

           Example:                     function compare ($x, $y)     {

                                    if ($x == $y)

return 0;

                                    else if ($x < $y)

return -1;

else

return 1;

}

 

$nums ( 10, 5, 15, 25);

usort ( $nums, compare );