Skip to content
UoL CS Notes

PHP - Arrays, Comparisons, Printing & NULL

COMP284 Lectures

Comparison Operators

Type juggling affects the way that comparisons work in PHP, consequently there are some additional competitors:

Expression Name Description
expr1 == expr2 Equal TRUE if expr1 is equal to expr2 after type juggling.
expr1 != expr2 Not Equal TRUE if expr1 is not equal to expr2 after type juggling.
expr1 <> expr2 Not Equal TRUE if expr1 is not equal to expr2 after type juggling.
expr1 === expr2 Identical TRUE if expr1 is equal to expr2 and they are the same type.
expr1 !== expr2 Identical TRUE if expr1 is not equal to expr2 or they are not the same type.

Comparing NAN and INF are also possible but may not behave as expected in PHP versions earlier than 5.3.

You can compare strings as strings using the following function:

Expression Name Description
strcmp(expr1, expr2) String Comparison Returns < 0 if expr1 is less than expr2,
> 0 if expr1 is greater than expr2,
0 of expr1 is equal to expr2.

You can convert strings to numbers and compare using the spaceship operator:

Expression Name Description
expr1 <=> expr2 Three-way Comparison Returns -1 if expr1 is less than expr2,
+1 if expr1 is greater than expr2,
0 of expr1 is equal to expr2.

NAN & INF Comparisons

PHP provides three functions to test whether a value is one of these values:

Expression Description
bool is_nan(<value>) Returns TRUE if the value is NAN.
bool is_infinite(<value>) Returns TRUE if the value is INF or -INF.
bool is_finite(<value>) Returns TRUE if the value is neither NAN nor INF or -INF.

Arrays

Creating Arrays

PHP only supports hash tables, hence they are just referred to as arrays. They are created like so:

array(key1 => value1, key2 => value2)
[key1 => value1, key2 => value2]
  • key - Is an integer or string.
  • value - Can be of any type, including arrays:

      $arr2 = array (200846369 = > array (
          "name" = > "Jan Olsen",
          "COMP201" = > 69,
          "COMP207" = > 52
          )
      );
    

The size of an array can be determined using the count function:

count(array[, mode])

using them on the above array would yield the following results:

print count($arr2);	// prints 1
print count($arr2, 1)	// prints 4

You can omit the keys when creating an array:

$arr3 = array("Peter", "Paul", "Mary");

This will automatically generate the keys as natural numbers (0, 1, …).

You can add a value to the end of an array using the following assingment:

$arr4[] = 51;	// 0 => 51
$arr4[] = 42;	// 1=> 42

Reading Arrays

All of the keys of an array can be fetched with the following function:

array_keys($array1)

this will return a natural number indexed array containing the keys of array1.

All of the values of an array can be fetched with the following function:

array_values($array1)

this will return a natural number indexed array containing the values stored in array1.

You can access an element of an array via its key:

$arr1 = array (1 => "Peter", 3 = > 2009, "a" => 101);
print "'a' = > " . $arr1 ["a"] . "\ n" ;
'a' => 101

Accessing an undefined key returns NULL.

You can use the following function to check if a key exists in an array:

array_key_exists("a", $arr1) // returns TRUE

foreach-loop

You can loop through all the mappings of an array using the following structure:

foreach (<array> as $value) {
	<statement>;
}

foreach (<array> as $key => $value) {
	<statement>;
}

Arrays are not sorted so the values are returned in insertion order.

In order to change the values of an array using a for each loop you need to use a reference (&):

foreach ($arr6 as $key => &$value) { // note the &
	$value .= " - modified";
}
  • This is required, otherwise a copy will be modified.
  • Unsetting the pointier is required to remove the structure from memory.
  • You can’t change the key, only the value.

Array Assignments

PHP uses copy-on-write for array assignments. This means that if you create a copy of an array:

$arr2 = $arr1;

they are treated as a reference to eachother (this saves the memory of writing it twice).

When one is changed:

$arr2[1] += 1000;

then the other copy is written to memory.

This means that $arr2 is no longer a pointer to $arr1 and is now its own array.

If you explicitly want a reference then you can do the following:

$arr2 = &$arr1;

This will create an alias for the same array.

Array Operators

PHP has no stack or queue datastructures. We can use the following functions with arrays to emulate these features:

Function Description
array_push(&$array, value1, value2, ...) Appends one, or more, elements at the end of an array. Returns the number of elements in the resulting array.
array_pop(&$array) Extracts the last element from an array and returns it.
array_shift(&$array) Extract the first element of an array and returns it.
array_unshift(&$array, value1, value2, ...) Inserts one or more elements at the start of an array variable. Returns the number of elements in the resulting array.

Printing

In PHP the default command for generating output is echo:

echo(arg1);
echo arg1, arg2, ...

No brackets are allowed if there is more than one argument.

This method is more efficient that printf so should be used when possible.

Additionally there are also the functions print and printf:

Function Description
print(arg) Takes one argument only and returns value 1. Brackets can be omitted.
printf(format, arg1, arg2, ...) Produces output according to format. Returns the length of the output string.
sprintf(format, arg1, arg2, ...) Returns a string produced according to the format.
vprintf(format array) Same as printf by accepts an array instead of comma separated values.
vsprintf(format, array) Same as sprintf and vprintf.

NULL

A variable can have the value and type of NULL in the following situations:

  • The variable has not yet been assigned a value.
  • The variable has been assigned the value NULL.
  • The variable has been unset.

You can use the following function to sets whether a variable is NULL:

Function Description
isset($variable) True if $variable exists and does not have value NULL.
is_null(expr) True if expr is identical to NULL.

Empty arrays are only loosely (==) equal to NULL but not identical (===).

Resources

A resource is a reference to an external file. We can use the following functions:

Function Description
fopen(filename, mode) Returns a file pointer for filename on success, false on error.
fclose(resource) Closes the resource. Returns true on success.
fgets(resource [, length]) Returns a line read from resource and returns false if there is no more data to read. length can be used to read the first $n$ characters, or until the end of the line.
fread(resource, length) Returns length charactesr read from resource.
fwrite(resource, string [, length]) Writes a string to a resource. If length is given, writing stops after length bytes, or the end of the string.
fprintf(resource, format, arg1, arg2, ...) Same as printf with output to resource.
vfprintf(resource, format, array) Same as vprintf with output to resource.

We can use the following modes:

Mode Operation Create Truncate
r Read File    
r+ Read/Write File    
w Write File Y Y
w+ Read/Write File Y Y
a Append File Y  
a+ Read/Append File Y  
x Write File Y  
x+ Read/Write File Y  

Here are some common file operations:

$handle = fopen('somefile.txt', 'r');
while ($line = fgets($handle)) {
	// processing each line
}
fclose($handle);
$handle = fopen('somefile.txt', 'w');
fwrite($handle, "Hello, World!".PHP_EOL);	// platform dependant newline
fclose($handle);