Cpsc110/Notes/Starting PHP

Contents

Introduction

This page provides a list of topics/notes based loosely on the material from Chapter 3 of Nixon, Learning PhP, MySQL, and Javascript.

Note that the book's examples are available on the website: Click here! As you are learning PHP, it would be a good practice to download and play with the examples. Just save them in a folder under your web folder, htdocs (Mac) or web (Windows), and open the examples with your browser.

Some useful references that you should consult:

PHP and HTML

PHP is embedded in HTML code by enclosing it within the <?php and ?> tags:

<HTML>
  <HEAD>
    <TITLE>Hello World</TITLE>
  </HEAD>
  <BODY>
    <?php echo "<P>This was printed by PHP.</P>"; ?>
  </BODY>
</HTML>

NOTE that some PHP parsers permit "<? ... ?>" to be used as PHP tags. But this is being deprecated.

Comments

Comments are used to document and clarify your code:

<HTML>
  <HEAD>
    <TITLE>Hello World</TITLE>
  </HEAD>
  <BODY>
    <?php 
        // This is a single line comment.

        /*
         * This is a multiline comment.
         */
        echo "<P>This was printed by PHP.</P>"; 
    ?>
  </BODY>
</HTML>

Basic Syntax

Semicolons

PHP commands must end with a semicolon:

echo "hello world";

The $ Symbol

The '$' symbol must precede all variable names. Three different types of variables in PHP are numbers, strings, and arrays:

<?php
   $aNumber = 1;
   $aString = "Hello";
   $anArray = array("one", "two", "three");  // An array of strings
?>

Variables

A variable is a memory location that stores a value of a particular type (a string such as "Hello" or a number such as 32).

A good way to think of variables is labeled matchboxes containing items.

In PHP variable names begin with $ and are defined as follows:

$variable_name = 54;

This command 'assigns' the value 54 to the variable named 'variable_name' (i.e., stores the value 54 in the matchbox labeled 'variable_name').

Variable Naming Rules

  • Preceeded by '$'.
  • Start with alphabetic letter or underscore (_).
  • Contain only a-z, A-Z, 0-9, and underscore (_).
  • No spaces.
  • Case sensitive: $foo is not the same as $Foo


String Variables

<?php // test1.php
   // To run this example, save it in your web directory and load it
   // into your browser with http://localhost/web/test1.php
   $username = "Peggy Programmer";
   echo $username;
   echo "<br />";  // HTML Line break
   $current_user = $username;
   echo $current_user;
?>

Numeric Variables

<?php
   $count = 17;
   $price = 17.99;
?>

Array Variables

<?php
   $class = array('Tiffany', 'Mark', 'Hazel', 'Grant');
   $seating_plan = array(array('george', 'bill', 'john'),
                      array('may', 'june', 'dorothy'),
                      array('florence', 'jim', 'ted'));
?>

Variable Type

Variables in PHP are loosely typed (different from Java). A variable's type is automatically picked by PHP when you assign it a value. If you assign it a number, then its type is numeric (or integer). PHP automatically performs certain conversions--e.g., "20"/2 = 10.


Operators (PHP Manual)

Arithmetic Operators

OperatorDescriptionExample
+Addition$j + 1
-Subtraction$j - 6
*Multiplication$j * 2
/Division$j / 3
%Modulus$j % 2
++Increment$++j
--Decrement$j--


Assignment Operators

OperatorExampleEquivalent to
=$j = 10$j = 10
+=$j += 5$j = $j + 5
-=$j -= 2$j = $j -2
*=$j *= 10$j = $j * 10
/=$j /= 3$j = $j / 3
.=$j .= $k$j = $j . $k
%=$j %= 2$j = $j % 2


Comparison Operators

OperatorDescriptionExample
==is equal to$j == 1
!=is not equal to$j != 6
>is greater than$j > 2
<is less than$j < 3
>=is greater than or equal to$j >= 2
<=is less than or equal to$j <= $k


Logical Operators

OperatorDescriptionExample
&&And$j == 3 && $k == 4
andlow-precedence and$j == 3 and $k == 4
||Or$j > 2 || $j < 0
orlow-precedence or$j > 2 or $j < 0
!Not!($j > 5)
xorexlusive or$j xor $k


String Examples

<?php
   $my_string = "Margaritaville - Suntan Oil Application!";
   echo "Margaritaville - Suntan Oil Application!<BR />";

   echo "Time for $my_string<BR />";

   $my_string = 'Margaritaville - Suntan Oil Application!';
   echo $my_string;
?>

Escape Characters

<?php
   //   \n (newline), \r (carriage return), \t (tabl), 
   //   \$ (dollar sign), \" (double quote)

   echo "<h2 class=\"specialH2\"Margaritaville!</h2>";
   echo '<h2 class="specialH2"Margaritaville!</h2>';
?>

Comparing Strings

String comparison operators include (PHP Manual):

operatormeaningnotes
==equal 
===identicalequal and the same type
!=not equal 
!==not identical
<>not equal
<less thancomes before in the alphabet
<=less than or equal to 
>=greater than or equal to 
>greater than 
Examples:
<?php
	$name1 = "Bill";
	$name2 = "BIll";
	if ($name1 > $name2) {
   		echo "$name1 > $name2<BR />";  
	}

	if ($name1 != $name2) {
   		echo "$name1 != $name2<BR />"; 
	}
	
	$number = 25;
	$number_string = "25";
	if ($number == $number_string) {
   		echo "$number == $number_string<BR />";  
	}	
	if ($number === $number_string) {
   		echo "$number === '$number_string'<BR />";  
	} else {
	   echo "$number !== '$number_string'<BR />";  
	}
?>

String Concatenation

Strings can be concatenated by using the period (.) operator:

<?php
   $str = "This is an example of " . 3 . " in the middle of a string";
   echo $str;
?>