"Welcome to our PHP 101 blog, where we demystify the world of web development. "

Friday, August 16, 2024

Lecture Notes 2. PHP Basics - Syntax and Data Types

Lecture Notes 2

PHP Basics - Syntax and Data Types


What is Syntax?

Syntax refers to the set of rules that define how PHP code should be written and structured. If you don't follow the syntax rules, PHP will throw an error, and your code won't work.

1. PHP Tags

Every PHP script starts and ends with PHP tags, which tell the server where the PHP code begins and ends. Here's the basic structure:

<?php

    // PHP code goes here

?>

You must write all PHP code between these tags. The server recognizes everything inside the tags as PHP code and processes it.

Example 1: 

Basic PHP Script

<?php

    echo "Hello, World!";

?> 

Explanation:

  1. We used the <?php tag to open the PHP code and ?> to close it.
  2. The echo statement outputs the text "Hello, World!" to the browser.

2. Comments in PHP

What are Comments?

Comments are lines in your code that are not executed by the PHP engine. They are meant for you (or other developers) to understand your code. You can use comments to explain what a particular part of the code does.

Types of Comments in PHP:

Single-line comments:

These are comments that span just one line. You can create them with either // or #.

// This is a single-line comment using //

# This is another single-line comment using #

Multi-line comments:

These comments span across multiple lines. They start with /* and end with */.

/*

   This is a multi-line comment.

   You can write comments on several lines.

*/

3. Displaying Output: 

Using echo and print

Using echo

echo is used to display output on the browser. You can display text, numbers, or variables with echo.

echo "Hello, World!";

Note: You do not need parentheses with echo, but you can use them if you want.

Using print

print is similar to echo, but it has one key difference: it returns a value (1), meaning it can be used in expressions.

print "Hello, PHP!";

Example:

<?php

    echo "Hello, World!";

    print " Welcome to PHP!";

?> 

Explanation: 

  1. This script will print "Hello, World!" followed by " Welcome to PHP!" on the web page.

4. Variables in PHP

What are Variables?

Variables are containers used to store data values. Think of a variable as a box that you can store information in, like a name or a number.

In PHP, all variables start with a dollar sign ($), followed by the variable's name.

Declaring a Variable

You can declare (create) a variable and assign a value to it like this:

$name = "John";  // String variable

$age = 25;       // Integer variable

Explanation:

  1. $name = "John";: Here, we create a variable called $name and assign the value "John" to it.
  2. $age = 25;: We create a variable called $age and assign the value 25 to it.

Rules for Variable Names:

  1. Variable names must start with a letter or an underscore (_).
  2. They cannot start with a number.
  3. Variable names are case-sensitive. $name and $Name are different variables.

Example 2: Display Variables

<?php

    $name = "Alice";

    $age = 22;

    echo "Name: " . $name . ", Age: " . $age;

?>

 

Explanation:

  1. We created two variables, $name and $age.
  2. We used echo to display the values of both variables by concatenating the text and variables using the . operator.
  3. The output will be: Name: Alice, Age: 22.

5. Data Types in PHP

What are Data Types?

Data types represent the different kinds of values that variables can hold. For example, a name is a string (text), while age is an integer (whole number).

Common Data Types in PHP:

1. String :

A string is a sequence of characters, like words or sentences, enclosed in quotes.

$greeting = "Hello, World!";

2 . Integer :

An integer is a whole number without any decimal places.

$age = 30;

3 . Float (Double)

A float is a number that has decimal points.

$price = 19.99;

4. Boolean

A boolean represents two possible states: TRUE or FALSE. Booleans are useful for conditions and logic.

$is_logged_in = true;

5. Array

An array is a variable that can hold multiple values. Think of it like a list of items.

$colors = array("Red", "Green", "Blue");

6. NULL

A NULL value represents a variable with no value assigned to it.

$data = NULL;

Example 3: Working with Data Types

<?php

    $name = "Charlie";   // String

    $age = 28;           // Integer

    $price = 9.99;       // Float

    $is_student = true;  // Boolean

    $colors = array("Red", "Green", "Blue"); // Array

    echo "Name: " . $name;

    echo " | Age: " . $age;

    echo " | Price: $" . $price;

    echo " | Is student: " . $is_student;

?> 

Explanation:

  1.  We created variables with different data types and used echo to display their values.

6. Type Casting in PHP

What is Type Casting?

  1. Type Casting is a process in PHP where a variable of one data type is explicitly converted into another data type. 
  2. This is done manually by the developer to ensure that a variable is treated as a specific type, especially when the context demands a particular data type for correct functionality.
  3. For instance, you might have a string that contains numeric data, but you want to perform mathematical operations on it. 
  4. By type casting, you can convert the string to a number before performing those operations.

Why Use Type Casting?

  1. To ensure compatibility with functions or operations that require a specific data type.
  2. To avoid unexpected behavior when variables automatically change types during operations.
  3. To enforce the type you want to work with, providing more control over the data.

Example: 

<?php

    $str_num = "100";  // String

    // Cast to integer

    $int_num = (int)$str_num;

    echo $int_num;  // Output: 100

?>

 

Explanation:

  1. $str_num is a string with the value "100". It is technically a series of characters.
  2. We use (int) to cast the string into an integer. This tells PHP to treat the value "100" as a number rather than a string.
  3. The output will be 100, and PHP now treats $int_num as an integer, allowing you to perform numerical operations on it.

Common Type Castings in PHP

In PHP, there are several types of casting that you can use depending on the data type you want to convert your variable to. 

Here are the most common ones:

1. Integer Casting ((int) or (integer))

This casts a variable to an integer. The string or float will be converted to a whole number.

Example

<?php

    $float_num = 12.7;  // Float

    // Cast to integer

    $int_num = (int)$float_num;

    echo $int_num;  // Output: 12

?>

 

Explanation:

  1. The value 12.7 is a floating-point number (a decimal number).
  2. We cast it to an integer using (int). This removes the decimal part, leaving 12.

2. Float Casting ((float) or (double) or (real))

This casts a variable to a floating-point number (a number with decimal points).

Example

<?php

    $str_num = "45.89";  // String

    // Cast to float

    $float_num = (float)$str_num;

    echo $float_num;  // Output: 45.89

?>

 

Explanation:

  1. We have a string "45.89", which represents a decimal number.
  2. Using (float), the string is converted into a float, allowing it to be used in mathematical calculations that require decimals.

3. Boolean Casting ((bool) or (boolean))

This casts a variable to a boolean. Any value can be cast to a boolean. Common rules include:

0, "", null are cast to false.

Non-zero numbers, non-empty strings are cast to true.

Example

<?php

    $num = 0;  // Integer

    // Cast to boolean

    $bool_value = (bool)$num;

    var_dump($bool_value);  // Output: bool(false)

?>

 

Explanation:

  1. The integer 0 is cast to a boolean. In PHP, 0 is considered as false.
  2. The var_dump function displays the data type and value, so the output is bool(false).

4. String Casting ((string))

This casts a variable to a string. Any data type can be converted to a string.

Example

<?php

    $int_num = 1234;  // Integer

    // Cast to string

    $str_value = (string)$int_num;

    echo $str_value;  // Output: "1234"

?>

 

Explanation:

  1. We have an integer 1234.
  2. Using (string), the integer is cast to a string, making it "1234".

5. Array Casting ((array))

This casts a variable to an array. A single scalar value is converted into an array with one element.

Example

<?php

    $num = 50;  // Integer

    // Cast to array

    $arr_value = (array)$num;

    print_r($arr_value);  // Output: Array ( [0] => 50 )

?>

 

Explanation:

  1. The integer 50 is cast to an array. 
  2. PHP creates an array with a single element, where the integer 50 is the value at index 0.

6. Object Casting ((object))

This casts a variable to an object. The variable is converted into an object with properties corresponding to its key-value pairs (in case of arrays) or value (in case of scalars).

Example

<?php

    $arr = ["name" => "John", "age" => 25];  // Array

    // Cast to object

    $obj_value = (object)$arr;

    echo $obj_value->name;  // Output: John

?>

 

Explanation:

  1. We have an associative array.
  2. Casting it to an object results in an object with properties corresponding to the keys of the array.

Automatic Type Casting (Type Juggling)

PHP is a loosely typed language, which means that it can automatically convert variables from one data type to another, depending on the context. This process is called Type Juggling.

Example:

<?php

    $x = "10";

    $y = 20;

    $result = $x + $y;  // Automatic casting from string to integer

    echo $result;  // Output: 30

?>

 

Explanation:

  1. In this example, PHP automatically converts the string "10" to an integer 10 when performing the addition operation.
  2. However, while PHP does automatic type juggling, it is good practice to use manual type casting when you want to ensure that your variable is treated as a specific type.


Conclusion

Type casting allows you to control how data is interpreted in your PHP scripts. It’s especially useful when working with different data types and ensuring that variables behave as expected in various operations. While PHP does a lot of type juggling automatically, explicit type casting gives you more control over the behavior of your code.






No comments:

Post a Comment

Pages

SoraTemplates

Best Free and Premium Blogger Templates Provider.

Buy This Template