Basic Syntax Revision
What is the standard way to start a PHP script?
- A) <?php
- B) <?
- C) <?=
- D) <script>
A) <?php
Explanation: The correct way to start a PHP script is by using <?php to indicate the beginning of the PHP code block. While <? is a shorthand used in some older versions of PHP, it is not recommended for compatibility reasons.
Which of the following is the correct way to comment a single-line in PHP?
- A) /* This is a comment */
- B) // This is a comment
- C) # This is a comment
- D) <!– This is a comment –>
In PHP, // is used for single- line comments. /* … */ is used for multi-line comments, and # is also valid for single-line comments, but // is more commonly used.
How do you concatenate two strings in PHP?
- A) string1 + string2
- B) string1 . string2
- C) string1 & string2
- D) string1 : string2
- Answer: B) string1 . string2
- Explanation: In PHP, the . (dot) operator is used for string concatenation. Using + will not concatenate strings; instead, it will perform arithmetic operations if both operands are numeric.
How do you end a PHP statement?
- A) ;
- B) :
- C) .
- D) ,
- Answer: A) ;
- Explanation: In PHP, statements are terminated with a semicolon ;. The semicolon is used to separate multiple statements on the same line or to mark the end of a single statement.
Which PHP language construct is used to output text to the web browser?
- A) echo()
- B) print()
- C) output()
- D) display()
- Both echo() and print() are used to output text to the web browser in PHP. However, echo() is slightly faster and more commonly used in practice.
BUT….
- Language Construct vs Function?
- Language constructs and built-in functions are often misinterpreted with one another due to the fact that both have more or less alike behavior.
- But they differ from each other in the way the PHP interpreter interprets them. Every programming language consists of tokens and structures which the respective language parser can recognize. So, whenever a file is parsed, the parser understands their usage and knows well what to do with them without having the need to examine them further. These tokens and structures are known as language construct. They are basically keywords that are a part of the programming language.
PHP VARIABLES, DATA TYPES AND CONSTANTS
PHP Variables
-
- Variables are used to store data, like string of text, numbers, etc. Variable values can change over the course of a script. Here’re some important things to know about variables:
- In PHP variable can be declared as: $var_name = value;
Naming Conventions for PHP Variables
These are the following rules for naming a PHP variable:
- All variables in PHP start with a $ sign, followed by the name of the variable.
- A variable name must start with a letter or the underscore character _.
- A variable name cannot start with a number.
- A variable name in PHP can only contain alpha-numeric characters and underscores (A-z, 0-9, and _).
- A variable name cannot contain spaces.
- PHP variables are case-sensitive, so $name and $NAME both are treated as different variable.
Which of the following is NOT a valid PHP variable name?
- A) $my_variable
- B) $_myVariable
- C) $1variable
- D) $myVariable123
Right Way of Writing Variables
Are you sure about the 4th one , $first-name?
Wrong Way
Data Type
Data Types in PHP
- PHP supports 3 types of data types:
- Predefined Data Types
- User-defined Data Types
- Special Data Types
Predefined Data Types
Also known as primitive data types, are the fundamental or built-in data types provided by the programming language. They are typically simple and have a fixed size in memory. Examples of primitive data types include integers, floating-point numbers, characters, booleans, and strings.
PHP Integers
- Integers hold only whole numbers including positive and negative numbers, i.e., numbers without fractional part or decimal point. (…, -2, -1, 0, 1, 2, …).
Facts for Nerds
- In PHP, the integer range is typically between -2^31 to 2^31, which represents the range of a signed 32-bit integer. This is because PHP (up until version 7.0) uses a 32-bit system, where integers are stored using 32 bits of memory.
- The range of a 32-bit signed integer is from – 2,147,483,648 to 2,147,483,647.
- Leftmost bit (the most significant bit) is used to represent the sign of the number: 0 for positive and 1 for negative. The remaining 31 bits are used to represent the magnitude of the number.
Integer overflow
- If PHP encounters a number beyond the bounds of the int type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the int type will return a float instead.
- $large_number = 9223372036854775807;
- var_dump($large_number);
- $large_number = 9223372036854775808;
- var_dump($large_number);
- $million = 1000000;
- $large_number = 50000000000000 * $million;
- var_dump($large_number);
PHP Floating Point Numbers or Doubles
- Floating point numbers (also known as “floats”, “doubles”, or “real numbers”) are decimal or fractional numbers
- Can hold numbers containing fractional or decimal parts including positive and negative numbers or a number in exponential form. By default, the variables add a minimum number of decimal places.
What is the result of the following PHP expression?
echo 0.1 + 0.2 – 0.3;
- 0.0
- A number close to 0
- 0
- 0.30000000000000004
What is the result of the following PHP expression? echo 0.1 + 0.2 – 0.3;
- 0.0
- A number close to 0
- 0
- 0.30000000000000004
Explanation
- Floating-point numbers in computers are stored using a binary representation, which can sometimes lead to precision errors when performing arithmetic operations. The expected result of the expression would be 0 (0.1 + 0.2 – 0.3), but due to the way floating-point numbers are represented in binary, there is a small rounding error that results in a value close to zero but not exactly zero.
- To handle such precision-critical calculations, it’s recommended to use techniques like rounding or formatting the output appropriately.
PHP Strings
- Strings are sequences of characters.
- A string can hold letters, numbers, and special characters and it can be as large as up to 2GB.(Theoretically it is possible , depends on memory)
- Hold letters or any alphabets, even numbers are included. These are written within double quotes during declaration. The strings can also be written within single quotes, but they will be treated differently while printing variables.
What will be the output of the following PHP code?
$str1 = “Hello”;
$str2 = ‘World’; echo $str1 + $str2;
Possible Answers:
- HelloWorld
- HelloWorld
- 0
- Error (Notice or Warning)
What will be the output of the following PHP code?
$str1 = “Hello”;
$str2 = ‘World’; echo $str1 + $str2;
Possible Answers:
- HelloWorld
- HelloWorld
- 0
- Error
Explanation
- In the given code, the + operator is used to perform addition. However, you cannot directly add two strings using the + operator in PHP. PHP will try to convert the strings to numbers and perform the addition, but it will encounter an error because they cannot be converted to valid numeric values. As a result, PHP throws a fatal error Uncaught TypeError: Unsupported operand types: string + string.
- To concatenate two strings in PHP, you should use the . (dot) operator, like this: $str1 . $str2;. This will concatenate the two strings and produce the output “HelloWorld”
PHP Booleans
- Booleans are like a switch it has only two possible values either 1 (true) or 0 (false).
What will be the output of the following PHP code?
$var1 = true;
$var2 = false;
echo $var1 + $var2; Possible Answers:
- 1
- 0
- true
- false
What will be the output of the following PHP code?
$var1 = true;
$var2 = false;
echo $var1 + $var2; Possible Answers:
- 1
- 0
- true
- false
Explanation
- In PHP, Boolean values true and false can be used in arithmetic expressions. When used in arithmetic operations, PHP considers true as 1 and false as 0. So, when you perform an arithmetic addition between
$var1 and $var2, PHP will treat them as numeric values and add them together.
- Since $var1 is true (which is equivalent to 1 in numeric context) and $var2 is false (which is equivalent to 0 in numeric context), the result of the expression $var1 + $var2 will be 1.
User Defined Data Types
User-defined data types, also called compound data types, are created by the programmer using various constructs provided by the programming language. These data types are composed of multiple primitive or compound data types, and they allow you to organize and store related data together. The most common user-defined data types are arrays and objects.
Initial PHP code
Rasmus during an Interview in 2003
- “I really don’t like programming. I built this tool to program less so that I could simply reuse code … I don’t know how to stop it, there was never any intention to write a programming language […]. I don’t know how to write a programming language at all, I just kept adding the next logical step.”
PHP Arrays
- An array is a variable that can hold more than one value at a time.
- It is useful to aggregate a series of related items together, for example a set of country or city names.
- An array is formally defined as an indexed collection of data values.
- Each index (also known as the key) of an array is unique and references a corresponding value.
What is the value of the $result
variable after executing the code?
$numbers = array(1, 2, 3, 4, 5);
$result = $numbers[0] + $numbers[1] + $numbers[2] +
$numbers[3] + $numbers[4];
- 15
- 10
- 120
- 25
What is the value of the $result variable after executing the code?
$numbers = array(1, 2, 3, 4, 5);
$result = $numbers[0] + $numbers[1] + $numbers[2] +
$numbers[3] + $numbers[4];
15
- 10
- 120
- 25
PHP Object
- An object is a data type that not only allows storing data but also information on, how to process that data.
- Objects are created via the new keyword.
- Every object has properties and methods corresponding to those of its parent class.
- Every object instance is completely independent, with its own properties and methods, and can thus be manipulated independently of other objects of the same class.
Code
- class Person {
- public $name;
public function sayHello() {
- echo “Hello, my name is ” . $this->name;
- }
- }
$person1 = new Person();
- $person1->name = “Baba Yaga”;
- $person1->sayHello(); // Output: Hello, my name is Baba Yaga
What does the PHP function var_dump() do?
- A) Outputs the value of a variable and its type
- B) Prints a message to the browser
- C) Dumps the contents of an array into a file
- D) Checks if a variable is defined
What does the PHP function var_dump() do?
- A) Outputs the value of a variable and its type
- B) Prints a message to the browser
- C) Dumps the contents of an array into a file
- D) Checks if a variable is defined
Special Data Types
These are often unique data types with specialized purposes, and they are not part of the standard data types provided by the language. In PHP, the “resource” data type is an example of a special data type. Resources are used to hold references to external resources, such as database connections or file handles.
PHP Null
- The special NULL value is used to represent empty variables in PHP.
- A variable of type NULL is a variable without any data. NULL is the only possible value of type null.
PHP Resources
- A resource is a special variable, holding a reference to an external resource.
- Resource variables typically hold special handlers to opened files and database connections.
Constants
- A constant is a name or an identifier for a fixed value.
- Constant are like variables, except that once they are defined, they cannot be undefined or changed.
- PHP constants can be defined by 2 ways:
- Using define() function
- Using const keyword
Constants(contd.)
- PHP constant: define() – Use the define() function to create a constant. It defines constant at run time. define(name, value)
-
- name: It specifies the constant name.
- value: It specifies the constant value.
Constants(contd.)
<?php
// case-sensitive constant name define(“WISHES”, “Good Evening”); echo WISHES;
?>
OUTPUT:
Good Evening
Constants(contd.)
- PHP constant: const keyword – PHP introduced a keyword const to create a constant. The const keyword defines constants at compile time. It is a language construct, not a function. The constant defined using const keyword are case-sensitive.
<?php
const WISHES=”Good day”; echo WISHES;
?> OUTPUT:
Good day
Constants(contd.)
- Constant() function – There is another way to print the value of constants using constant() function.
- The syntax for the following constant function:
constant (name)
Constants(contd.)
<?php
define(“WISHES”, “Good Evening”); echo WISHES. “<br>”;
echo constant(“WISHES”);
//both are similar
?>
OUTPUT:
Good Evening Good Evening
Constants(contd.)
- PHP Constant Arrays – In PHP, you can create an Array constant using the define() function.
<?php define(“courses”, [ “PHP”,
“HTML”, “CSS”
]);
echo courses[0];
?> OUTPUT: PHP
Constants(contd.)
- PHP Constant Arrays – In PHP, you can also create an Array constant using const keyword.
<?php
const WISHES=array(“PHP”,
“HTML”,
“CSS”);
echo WISHES[0];
?>
OUTPUT: PHP
Constants(contd.)
- Constants are Global – Constants are automatically global and can be used across the entire script.
<?php
define(“WISHES”, “Good Evening”);
function test() { echo WISHES;
}
test();
?>
OUTPUT:
Good Evening
Developers hate PHP because you are more likely to get errors with a language that allows so much freedom.
[pdf_note link=”https://drive.google.com/file/d/1gXFX_2bDuZpfq6TfY8qgFL1iquuc37pH/view”]