Module 2 - Variables and Types

PHP Tags

In PHP, tags are used to delineate and enclose blocks of PHP code within an HTML document. PHP code should be enclosed in these tags to indicate to the server that the content within them should be processed as PHP code. There are two primary types of PHP tags used for this purpose: the standard PHP tags and the short PHP tags.

Standard PHP Tags:

Opening Tag: <?php
Closing Tag: ?>

The standard PHP tags are the most commonly used and recommended way to enclose PHP code. Anything between <?php and ?> is treated as PHP code and will be executed on the server.

Example:

<?php
$name = "John";
echo "Hello, $name!";
?>

Short PHP Tags (Short Open Tags):

Opening Tag: <?
Closing Tag: ?>

Short tags are a more concise way of embedding PHP code within HTML. However, their use is discouraged because they may not be enabled on all PHP configurations, and they can conflict with XML declarations. Using short tags can also make code less portable.

Example:

<?
$name = "John";
echo "Hello, $name!";
?>

It's essential to understand the context in which you're using PHP tags:

Within HTML:

 When you want to embed PHP code within an HTML document, you typically use the standard PHP tags or the short PHP tags. These tags allow you to generate dynamic content or perform server-side processing within an HTML page.

Example:

<html>
<head>
<title>PHP Example</title>
</head>
<body>
<h1><?php echo "Hello, World!"; ?></h1>
</body>
</html>

Within a Pure PHP File:

In PHP files that contain only PHP code and no HTML, you don't need to use closing tags. It's common practice to omit the closing ?> tag at the end of the file to prevent unintended whitespace or newline characters from being sent to the browser.

Example:

<?php
$name = "Alice";
echo "Hello, $name!";
// No closing tag here

In summary, PHP tags are used to enclose blocks of PHP code within an HTML document or a standalone PHP file. The choice between standard PHP tags and short PHP tags depends on your project's requirements and compatibility considerations, but standard PHP tags are generally recommended for broader compatibility and code portability.



Variables in PHP

Variables in PHP serve as containers for storing and managing data. They help in handling information in the form of numbers, text, arrays, objects, and other data. Here is a detailed description of variables in PHP, including naming rules, best practices for usage, and limitations:

1. Variable Naming Rules:

  • Variable names in PHP must begin with a dollar sign ($) followed by the variable name.
  • Variable names are case-sensitive, meaning that $name and $Name are treated as distinct variables.
  • Variable names can consist of letters, numbers, and underscores, but they must start with a letter or an underscore.
  • Variable names should not include spaces or special characters, except underscores.
  • Variable names should avoid using PHP reserved words or keywords such as if, else, while, etc.
  • Variables should not start with a number, but they can contain numbers after the initial letter.

Proper Variable Naming:

Variable names should be descriptive and meaningful to enhance code readability and maintainability. For example, using $firstName as a variable name is more meaningful than $fn.

2. Variable Assignment:

To assign values to variables in PHP, you use the assignment operator (=). The variable takes on the data type of the assigned value.

Example:

$age = 30;
$name = "Alice";

3. Variable Scope:

Variables in PHP have different scopes that determine where they can be accessed within the code:

Local Scope: Variables declared inside a function have local scope and are accessible only within that function.
Global Scope: Variables declared outside of any function have global scope and can be accessed throughout the script.

Example:

$globalVar = 42; // Global variable

function myFunction() {
$localVar = 10; // Local variable
echo $globalVar; // Accessing a global variable
}

4. Variable Reassignment:

You can change the value of a variable by merely assigning a new value to it. The variable's data type can change accordingly.

Example:

$age = 25;  // $age is an integer
$age = "thirty"; // $age is now a string

5. Variable Limitations:

  1. Variable names are restricted to 64 characters.
  2. Variables cannot commence with a number, but they can include numbers.
  3. Reserved words or keywords should not be used as variable names.
  4. Variables are case-sensitive; $myVar and $myvar are considered as separate variables.

6. Proper Usage:

  • Utilize descriptive and meaningful variable names to enhance code readability.
  • Avoid using reserved words or keywords as variable names.
  • Adhere to consistent naming conventions, such as camelCase or snake_case.
  • Ensure appropriate scoping of variables to prevent naming conflicts and maintain data integrity.

Variables are a fundamental concept in PHP and are extensively used for data management in web development. Proper naming, scoping, and usage of variables are essential for writing clean and maintainable code in PHP.



Data Types in PHP

Data types in PHP define the type of data that can be stored in variables. Understanding data types is essential for proper data manipulation and ensuring that your code functions as expected. PHP supports several core data types, which can be categorized into the following groups:

Scalar Data Types:

Integers (int): 

Integers are whole numbers without a decimal point. They can be positive or negative.

Limitations: The range of integer values in PHP depends on the system's architecture (32-bit or 64-bit). For 32-bit systems, it's typically from -2,147,483,648 to 2,147,483,647.

$age = 25;
$quantity = -10;

Floating-Point Numbers (float or double): 

Floating-point numbers, often referred to as "floats" or "doubles," represent numbers with a decimal point.

Limitations: Floating-point numbers are approximate representations, which can lead to precision issues in some calculations.

Example:

$price = 19.99;
$pi = 3.14159265359;

Strings (string): 

Strings are sequences of characters, including letters, numbers, and symbols.

Limitations: The maximum length of a string is determined by the available memory.

Example:

$name = "Alice";
$address = '123 Main St';

Booleans (bool):

Booleans represent true or false values.

Limitations: Booleans can only have two values: true or false.

Example:

$isStudent = true;
$isWorking = false;

Compound Data Types:

Arrays: 

Arrays in PHP are ordered collections of data, allowing you to store multiple values in a single variable.

Limitations: Arrays can hold values of mixed data types.

Example:

$fruits = ["apple", "banana", "cherry"];
$person = ["name" => "John", "age" => 30];

Objects

Objects are instances of user-defined classes, encapsulating both data and methods.

Limitations: Objects are not built-in data types; they are defined by the programmer based on class definitions.

Example:

class Person {
public $name;
public $age;
}

$person = new Person();
$person->name = "Alice";
$person->age = 25;

Special Data Types:

NULL: 

NULL is a special data type representing the absence of a value.

Limitations: NULL is not the same as an empty string or zero; it indicates the complete absence of a value.

Example:

$uninitializedVar = NULL;

These data types are the building blocks of PHP programming. Understanding their characteristics and limitations is crucial for effective data handling and manipulation in PHP applications. Choosing the appropriate data type for your variables is essential for efficient and bug-free code.



Getting Form Data

HTML forms act like containers that gather user data, and then send it to a processing script. In this case, our processing script is PHP.  We will cover more advanced form elements as we go deeper into PHP, as well as how to dynamically handle them and how to make sure user input is valid.  For now, though, we will start out with a basic text field, and see how the web server and PHP handle the data.

Each form on a web page groups together several form fields, and then dictates two things about those fields:

1. Where they are sent (this is a URL representing a web script). This is specified using the action attribute of the form.

2. How the data is encoded and sent (this is almost always either "get" or "post"). This. is specified using the method attribute in the form tag.

form with action="a2_script.php" and method="post"

The form tag above will send all of the form's data to the script called a2_script.php using the post method.  For this assignment, we will use post - We will play around with get later in the course.  For now, here are a few things about get and post so you can think through which one to use for any given situation:

post - This method sends the data as part of the http headers.  What you really need to know is that the data isn't visible to the average user.  Using post, you can also send multiple types of data, including files.  This method is slightly more secure than get, but it is a little less flexible.

get - The get method sends the form data as part of a URL-encoded querystring.  This limits what you can send (no files), but it offers a tremendous amount of flexibility.  In addition to forms, you can use links and other methods to trigger a querystring request.  This is a technique that we will use throughout the rest of the class.

Many web applications use a combination of get and post to function.  It's good to get comfortable with both.

Let's look at how we might use post to send two form fields to a php script that just displays the data.  First, let's take a look at the form html:

HTML code showing the elements of a form with two text fields.

Looking at the code above, we can see (1) the action is set to send the form data to a2_script.php, which is a php file on the same directory on the same server.  This could be any valid URL, including one that points to a remote server.  The method (2) is set to post.  The other two important elements to pay attention to, (3) and (4), are the names of the form fields.  These names are what we will use to retrieve the form data from the post, so we can do something with it.

Here is what the form looks like with a litte CSS applied to it:

A login form, showing two form fields.

While you can't see the names, the text fields from the code above are here, labeled (1) and (2).  You can't see the method and action either. This is deliberate, because we want to give the user a good experience using the form.  They should have to worry about how it works, as long as it does work.

Now let's look at the php code that we will use to grab the data that's sent in a2_script.php:

$strUsername = $_POST["username"];
$strPassword = $_POST["password"];
echo("The username is $strUsername");
echo("The password is $strPassword");

There are four lines of code, but really only two since the lines are repeated for each piece of data.  The first line creates a variable called $strUsername and uses $_POST to get the data from the "username" form field and put it into that variable.  On the third line, you can see that we are using the echo ( ) function to print the value of the variable as part of the sentence "The username is ______ ."  The second and fourth lines of code do something similar with the password field.  This prints out everything as regular text, but if we embed this code into an HTML document we can use CSS to style it and JavaScript to make it interactive.  This is the basic building block for how web applications are made.



Properties of Strings

Strings are fundamental data types in PHP, used to represent sequences of characters, such as letters, numbers, symbols, and whitespace. Here are some key properties of strings in PHP:

  • Text Representation: Strings can contain text data, making them suitable for storing and manipulating textual information like names, addresses, or messages.
  • Character Encoding: PHP supports various character encodings, including UTF-8, which allows you to work with characters from different languages and special symbols.
  • Immutability: In PHP, strings are immutable, meaning that once created, their content cannot be modified. Any operation that appears to modify a string actually creates a new string with the desired changes.
  • Escaping Characters: Strings can contain special characters like double quotes (") or backslashes (\). To include these characters in a string, you can escape them using a backslash (e.g., \" for double quotes).
  • Concatenation: You can concatenate (combine) strings using the concatenation operator (.). For example, $first = "Hello, "; and $second = "World!";, and $greeting = $first . $second; results in $greeting containing "Hello, World!".
  • Interpolation: PHP allows you to insert the value of a variable into a double-quoted string. This is known as variable interpolation.
  • Functions and Methods: PHP provides a wide range of functions and methods for working with strings, including functions for manipulating, searching, and formatting strings.

Differences Between Single, Double, and Triple Quotes:

In PHP, you can define strings using single quotes (') or double quotes ("). 

Each has specific behavior and use cases:

Single Quotes (''):

Text within single quotes is treated literally, and special characters (except for \\ and \') are not interpreted.
Variables are not interpolated within single-quoted strings. They are treated as plain text.

Example:

$name = "Alice";
echo 'Hello, $name!'; // Output: Hello, $name!

Double Quotes (""):

Text within double quotes allows the interpretation of variables and escape sequences. Variable interpolation occurs, and escape sequences (e.g., \", \\) are recognized and replaced.

Example:

$name = "Alice";
echo "Hello, $name!"; // Output: Hello, Alice!

In summary, single quotes treat strings as literal text, double quotes allow variable interpolation and escape sequences. Your choice of quotes depends on the specific requirements of your string and how you want it to be processed by PHP.

Videos for Module 2 - Variables and Types

There are no videos yet this term for this Module. Check back soon!