• Language Reference

Assignment Operators

The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the right (that is, "gets set to").

The value of an assignment expression is the value assigned. That is, the value of " $a = 3 " is 3. This allows you to do some tricky things: <?php $a = ( $b = 4 ) + 5 ; // $a is equal to 9 now, and $b has been set to 4. ?>

In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic , array union and string operators that allow you to use a value in an expression and then set its value to the result of that expression. For example: <?php $a = 3 ; $a += 5 ; // sets $a to 8, as if we had said: $a = $a + 5; $b = "Hello " ; $b .= "There!" ; // sets $b to "Hello There!", just like $b = $b . "There!"; ?>

Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. This may also have relevance if you need to copy something like a large array inside a tight loop.

An exception to the usual assignment by value behaviour within PHP occurs with object s, which are assigned by reference. Objects may be explicitly copied via the clone keyword.

Assignment by Reference

Assignment by reference is also supported, using the " $var = &$othervar; " syntax. Assignment by reference means that both variables end up pointing at the same data, and nothing is copied anywhere.

Example #1 Assigning by reference

The new operator returns a reference automatically, as such assigning the result of new by reference is an error.

The above example will output:

More information on references and their potential uses can be found in the References Explained section of the manual.

Arithmetic Assignment Operators

Example Equivalent Operation
$a += $b $a = $a + $b Addition
$a -= $b $a = $a - $b Subtraction
$a *= $b $a = $a * $b Multiplication
$a /= $b $a = $a / $b Division
$a %= $b $a = $a % $b Modulus
$a **= $b $a = $a ** $b Exponentiation

Bitwise Assignment Operators

Example Equivalent Operation
$a &= $b $a = $a & $b Bitwise And
$a |= $b $a = $a | $b Bitwise Or
$a ^= $b $a = $a ^ $b Bitwise Xor
$a <<= $b $a = $a << $b Left Shift
$a >>= $b $a = $a >> $b Right Shift

Other Assignment Operators

Example Equivalent Operation
$a .= $b $a = $a . $b String Concatenation
$a ??= $b $a = $a ?? $b Null Coalesce
  • arithmetic operators
  • bitwise operators
  • null coalescing operator

Improve This Page

User contributed notes 4 notes.

To Top

Tutorials Class - Logo

  • PHP All Exercises & Assignments

Practice your PHP skills using PHP Exercises & Assignments. Tutorials Class provides you exercises on PHP basics, variables, operators, loops, forms, and database.

Once you learn PHP, it is important to practice to understand PHP concepts. This will also help you with preparing for PHP Interview Questions.

Here, you will find a list of PHP programs, along with problem description and solution. These programs can also be used as assignments for PHP students.

Write a program to count 5 to 15 using PHP loop

Description: Write a Program to display count, from 5 to 15 using PHP loop as given below.

Rules & Hint

  • You can use “for” or “while” loop
  • You can use variable to initialize count
  • You can use html tag for line break

View Solution/Program

5 6 7 8 9 10 11 12 13 14 15

Write a program to print “Hello World” using echo

Description: Write a program to print “Hello World” using echo only?

Conditions:

  • You can not use any variable.

View Solution /Program

Hello World

Write a program to print “Hello PHP” using variable

Description: Write a program to print “Hello PHP” using php variable?

  • You can not use text directly in echo but can use variable.

Write a program to print a string using echo+variable.

Description: Write a program to print “Welcome to the PHP World” using some part of the text in variable & some part directly in echo.

  • You have to use a variable that contains string “PHP World”.

Welcome to the PHP World

Write a program to print two variables in single echo

Description: Write a program to print 2 php variables using single echo statement.

  • First variable have text “Good Morning.”
  • Second variable have text “Have a nice day!”
  • Your output should be “Good morning. Have a nice day!”
  • You are allowed to use only one echo statement in this program.

Good Morning. Have a nice day!

Write a program to check student grade based on marks

Description:.

Write a program to check student grade based on the marks using if-else statement.

  • If marks are 60% or more, grade will be First Division.
  • If marks between 45% to 59%, grade will be Second Division.
  • If marks between 33% to 44%, grade will be Third Division.
  • If marks are less than 33%, student will be Fail.

Click to View Solution/Program

Third Division

Write a program to show day of the week using switch

Write a program to show day of the week (for example: Monday) based on numbers using switch/case statements.

  • You can pass 1 to 7 number in switch
  • Day 1 will be considered as Monday
  • If number is not between 1 to 7, show invalid number in default

It is Friday!

Write a factorial program using for loop in php

Write a program to calculate factorial of a number using for loop in php.

The factorial of 3 is 6

Factorial program in PHP using recursive function

Exercise Description: Write a PHP program to find factorial of a number using recursive function .

What is Recursive Function?

  • A recursive function is a function that calls itself.

Write a program to create Chess board in PHP using for loop

Write a PHP program using nested for loop that creates a chess board.

  • You can use html table having width=”400px” and take “30px” as cell height and width for check boxes.

Chess-board-in-PHP-using-for-loop

Write a Program to create given pattern with * using for loop

Description: Write a Program to create following pattern using for loops:

  • You can use for or while loop
  • You can use multiple (nested) loop to draw above pattern

View Solution/Program using two for loops

* ** *** **** ***** ****** ******* ********

Simple Tips for PHP Beginners

When a beginner start PHP programming, he often gets some syntax errors. Sometimes these are small errors but takes a lot of time to fix. This happens when we are not familiar with the basic syntax and do small mistakes in programs. These mistakes can be avoided if you practice more and taking care of small things.

I would like to say that it is never a good idea to become smart and start copying. This will save your time but you would not be able to understand PHP syntax. Rather, Type your program and get friendly with PHP code.

Follow Simple Tips for PHP Beginners to avoid errors in Programming

  • Start with simple & small programs.
  • Type your PHP program code manually. Do not just Copy Paste.
  • Always create a new file for new code and keep backup of old files. This will make it easy to find old programs when needed.
  • Keep your PHP files in organized folders rather than keeping all files in same folder.
  • Use meaningful names for PHP files or folders. Some examples are: “ variable-test.php “, “ loops.php ” etc. Do not just use “ abc.php “, “ 123.php ” or “ sample.php “
  • Avoid space between file or folder names. Use hyphens (-) instead.
  • Use lower case letters for file or folder names. This will help you make a consistent code

These points are not mandatory but they help you to make consistent and understandable code. Once you practice this for 20 to 30 PHP programs, you can go further with more standards.

The PHP Standard Recommendation (PSR) is a PHP specification published by the PHP Framework Interop Group.

Experiment with Basic PHP Syntax Errors

When you start PHP Programming, you may face some programming errors. These errors stops your program execution. Sometimes you quickly find your solutions while sometimes it may take long time even if there is small mistake. It is important to get familiar with Basic PHP Syntax Errors

Basic Syntax errors occurs when we do not write PHP Code correctly. We cannot avoid all those errors but we can learn from them.

Here is a working PHP Code example to output a simple line.

Output: Hello World!

It is better to experiment with PHP Basic code and see what errors happens.

  • Remove semicolon from the end of second line and see what error occurs
  • Remove double quote from “Hello World!” what error occurs
  • Remove PHP ending statement “?>” error occurs
  • Use “
  • Try some space between “

Try above changes one at a time and see error. Observe What you did and what error happens.

Take care of the line number mentioned in error message. It will give you hint about the place where there is some mistake in the code.

Read Carefully Error message. Once you will understand the meaning of these basic error messages, you will be able to fix them later on easily.

Note: Most of the time error can be found in previous line instead of actual mentioned line. For example: If your program miss semicolon in line number 6, it will show error in line number 7.

Using phpinfo() – Display PHP Configuration & Modules

phpinfo()   is a PHP built-in function used to display information about PHP’s configuration settings and modules.

When we install PHP, there are many additional modules also get installed. Most of them are enabled and some are disabled. These modules or extensions enhance PHP functionality. For example, the date-time extension provides some ready-made function related to date and time formatting. MySQL modules are integrated to deal with PHP Connections.

It is good to take a look on those extensions. Simply use

phpinfo() function as given below.

Example Using phpinfo() function

Using-phpinfo-Display-PHP-Configuration-Modules

Write a PHP program to add two numbers

Write a program to perform sum or addition of two numbers in PHP programming. You can use PHP Variables and Operators

PHP Program to add two numbers:

Write a program to calculate electricity bill in php.

You need to write a PHP program to calculate electricity bill using if-else conditions.

  • For first 50 units – Rs. 3.50/unit
  • For next 100 units – Rs. 4.00/unit
  • For next 100 units – Rs. 5.20/unit
  • For units above 250 – Rs. 6.50/unit
  • You can use conditional statements .

assignment with php

Write a simple calculator program in PHP using switch case

You need to write a simple calculator program in PHP using switch case.

Operations:

  • Subtraction
  • Multiplication

simple-calculator-program-in-PHP-using-switch-case

Remove specific element by value from an array in PHP?

You need to write a program in PHP to remove specific element by value from an array using PHP program.

Instructions:

  • Take an array with list of month names.
  • Take a variable with the name of value to be deleted.
  • You can use PHP array functions or foreach loop.

Solution 1: Using array_search()

With the help of  array_search()  function, we can remove specific elements from an array.

array(4) { [0]=> string(3) “jan” [1]=> string(3) “feb” [3]=> string(5) “april” [4]=> string(3) “may” }

Solution 2: Using  foreach()

By using  foreach()  loop, we can also remove specific elements from an array.

array(4) { [0]=> string(3) “jan” [1]=> string(3) “feb” [3]=> string(5) “april” [4]=> string(3) “may” }

Solution 3: Using array_diff()

With the help of  array_diff()  function, we also can remove specific elements from an array.

array(4) { [0]=> string(3) “jan” [1]=> string(3) “feb” [2]=> string(5) “march” [4]=> string(3) “may” }

Write a PHP program to check if a person is eligible to vote

Write a PHP program to check if a person is eligible to vote or not.

  • Minimum age required for vote is 18.
  • You can use PHP Functions .
  • You can use Decision Making Statements .

Click to View Solution/Program.

You Are Eligible For Vote

Write a PHP program to calculate area of rectangle

Write a PHP program to calculate area of rectangle by using PHP Function.

  • You must use a PHP Function .
  • There should be two arguments i.e. length & width.

View Solution/Program.

Area Of Rectangle with length 2 & width 4 is 8 .

  • Next »
  • PHP Exercises Categories
  • PHP Top Exercises
  • PHP Variables
  • PHP Decision Making
  • PHP Functions
  • PHP Operators

Home » PHP Tutorial » PHP Assignment Operators

PHP Assignment Operators

Summary : in this tutorial, you will learn about the most commonly used PHP assignment operators.

Introduction to the PHP assignment operator

PHP uses the = to represent the assignment operator. The following shows the syntax of the assignment operator:

On the left side of the assignment operator ( = ) is a variable to which you want to assign a value. And on the right side of the assignment operator ( = ) is a value or an expression.

When evaluating the assignment operator ( = ), PHP evaluates the expression on the right side first and assigns the result to the variable on the left side. For example:

In this example, we assigned 10 to $x, 20 to $y, and the sum of $x and $y to $total.

The assignment expression returns a value assigned, which is the result of the expression in this case:

It means that you can use multiple assignment operators in a single statement like this:

In this case, PHP evaluates the right-most expression first:

The variable $y is 20 .

The assignment expression $y = 20 returns 20 so PHP assigns 20 to $x . After the assignments, both $x and $y equal 20.

Arithmetic assignment operators

Sometimes, you want to increase a variable by a specific value. For example:

How it works.

  • First, $counter is set to 1 .
  • Then, increase the $counter by 1 and assign the result to the $counter .

After the assignments, the value of $counter is 2 .

PHP provides the arithmetic assignment operator += that can do the same but with a shorter code. For example:

The expression $counter += 1 is equivalent to the expression $counter = $counter + 1 .

Besides the += operator, PHP provides other arithmetic assignment operators. The following table illustrates all the arithmetic assignment operators:

OperatorExampleEquivalentOperation
+=$x += $y$x = $x + $yAddition
-=$x -= $y$x = $x – $ySubtraction
*=$x *= $y$x = $x * $yMultiplication
/=$x /= $y$x = $x / $yDivision
%=$x %= $y$x = $x % $yModulus
**=$z **= $y$x = $x ** $yExponentiation

Concatenation assignment operator

PHP uses the concatenation operator (.) to concatenate two strings. For example:

By using the concatenation assignment operator you can concatenate two strings and assigns the result string to a variable. For example:

  • Use PHP assignment operator ( = ) to assign a value to a variable. The assignment expression returns the value assigned.
  • Use arithmetic assignment operators to carry arithmetic operations and assign at the same time.
  • Use concatenation assignment operator ( .= )to concatenate strings and assign the result to a variable in a single statement.
  • TutorialKart
  • SAP Tutorials
  • Salesforce Admin
  • Salesforce Developer
  • Visualforce
  • Informatica
  • Kafka Tutorial
  • Spark Tutorial
  • Tomcat Tutorial
  • Python Tkinter

Programming

  • Bash Script
  • Julia Tutorial
  • CouchDB Tutorial
  • MongoDB Tutorial
  • PostgreSQL Tutorial
  • Android Compose
  • Flutter Tutorial
  • Kotlin Android

Web & Server

  • Selenium Java
  • PHP Tutorial
  • PHP Install
  • PHP Hello World
  • Check if variable is set
  • Convert string to int
  • Convert string to float
  • Convert string to boolean
  • Convert int to string
  • Convert int to float
  • Get type of variable
  • Subtraction
  • Multiplication
  • Exponentiation
  • Simple Assignment
  • Addition Assignment
  • Subtraction Assignment
  • ADVERTISEMENT
  • Multiplication Assignment
  • Division Assignment
  • Modulus Assignment
  • PHP Comments
  • Python If AND
  • Python If OR
  • Python If NOT
  • Do-While Loop
  • Nested foreach
  • echo() vs print()
  • printf() vs sprintf()
  • PHP Strings
  • Create a string
  • Create empty string
  • Compare strings
  • Count number of words in string
  • Get ASCII value of a character
  • Iterate over characters of a string
  • Iterate over words of a string
  • Print string to console
  • String length
  • Substring of a string
  • Check if string is empty
  • Check if strings are equal
  • Check if strings are equal ignoring case
  • Check if string contains specified substring
  • Check if string starts with specific substring
  • Check if string ends with specific substring
  • Check if string starts with specific character
  • Check if string starts with http
  • Check if string starts with a number
  • Check if string starts with an uppercase
  • Check if string starts with a lowercase
  • Check if string ends with a punctuation
  • Check if string ends with forward slash (/) character
  • Check if string contains number(s)
  • Check if string contains only alphabets
  • Check if string contains only numeric digits
  • Check if string contains only lowercase
  • Check if string contains only uppercase
  • Check if string value is a valid number
  • Check if string is a float value
  • Append a string with suffix string
  • Prepend a string with prefix string
  • Concatenate strings
  • Concatenate string and number
  • Insert character at specific index in string
  • Insert substring at specific index in string
  • Repeat string for N times
  • Replace substring
  • Replace first occurrence
  • Replace last occurrence
  • Trim spaces from edges of string
  • Trim specific characters from edges of the string
  • Split string
  • Split string into words
  • Split string by comma
  • Split string by single space
  • Split string by new line
  • Split string by any whitespace character
  • Split string by one or more whitespace characters
  • Split string into substrings of specified length
  • Transformations
  • Reverse a string
  • Convert string to lowercase
  • Convert string to uppercase
  • Join elements of string array with separator string
  • Delete first character of string
  • Delete last character of string
  • Count number of occurrences of substring in a string
  • Count alphabet characters in a string
  • Find index of substring in a string
  • Find index of last occurrence in a string
  • Find all the substrings that match a pattern
  • Check if entire string matches a regular expression
  • Check if string has a match for regular expression
  • Sort array of strings
  • Sort strings in array based on length
  • Foramatting
  • PHP – Format string
  • PHP – Variable inside a string
  • PHP – Parse JSON String
  • Conversions
  • PHP – Convert CSV String into Array
  • PHP – Convert string array to CSV string
  • Introduction to Arrays
  • Indexed arrays
  • Associative arrays
  • Multi-dimensional arrays
  • String array
  • Array length
  • Create Arrays
  • Create indexed array
  • Create associative array
  • Create empty array
  • Check if array is empty
  • Check if specific element is present in array .
  • Check if two arrays are equal
  • Check if any two adjacent values are same
  • Read/Access Operations
  • Access array elements using index
  • Iterate through array using For loop
  • Iterate over key-value pairs using foreach
  • Array foreach()
  • Get first element in array
  • Get last element in array
  • Get keys of array
  • Get index of a key in array
  • Find Operations
  • Count occurrences of specific value in array
  • Find index of value in array
  • Find index of last occurrence of value in array
  • Combine two arrays to create an Associative Array
  • Convert array to string
  • Convert array to CSV string
  • Join array elements
  • Reverse an array
  • Split array into chunks
  • Slice array by index
  • Slice array by key
  • Preserve keys while slicing array
  • Truncate array
  • Remove duplicate values in array
  • Filter elements in array based on a condition
  • Filter positive numbers in array
  • Filter negative numbers in array
  • Remove empty strings in array
  • Delete Operations
  • Delete specific value from array
  • Delete value at specific index in array
  • Remove first value in array
  • Remove last value in array
  • Array - Notice: Undefined offset: 0
  • JSON encode
  • Array Functions
  • array_chunk()
  • array_column()
  • array_combine()
  • array_change_key_case()
  • array_count_values()
  • array_diff_assoc()
  • array_diff_key()
  • array_diff_uassoc()
  • array_diff_ukey()
  • array_diff()
  • array_fill()
  • array_fill_keys()
  • array_flip()
  • array_key_exists()
  • array_keys()
  • array_pop()
  • array_product()
  • array_push()
  • array_rand()
  • array_replace()
  • array_sum()
  • array_values()
  • Create an object or instance
  • Constructor
  • Constants in class
  • Read only properties in class
  • Encapsulation
  • Inheritance
  • Define property and method with same name in class
  • Uncaught Error: Cannot access protected property
  • Nested try catch
  • Multiple catch blocks
  • Catch multiple exceptions in a single catch block
  • Print exception message
  • Throw exception
  • User defined Exception
  • Get current timestamp
  • Get difference between two given dates
  • Find number of days between two given dates
  • Add specific number of days to given date
  • ❯ PHP Tutorial
  • ❯ PHP Operators
  • ❯ Assignment

PHP Assignment Operators

In this tutorial, you shall learn about Assignment Operators in PHP, different Assignment Operators available in PHP, their symbols, and how to use them in PHP programs, with examples.

Assignment Operators

Assignment Operators are used to perform to assign a value or modified value to a variable.

Assignment Operators Table

The following table lists out all the assignment operators in PHP programming.

OperatorSymbolExampleDescription
Simple Assignment=x = 5Assigns value of 5 to variable x.
Addition Assignment+= Assigns the result of to x.
Subtraction Assignment-= Assigns the result of to x.
Multiplication Assignment*= Assigns the result of to x.
Division Assignment/= Assigns the result of to x.
Modulus Assignment%= Assigns the result of to x.

In the following program, we will take values in variables $x and $y , and perform assignment operations on these values using PHP Assignment Operators.

PHP Program

Assignment Operators in PHP

Assignment Operators Tutorials

The following tutorials cover each of the Assignment Operators in PHP in detail with examples.

  • PHP Simple Assignment
  • PHP Addition Assignment
  • PHP Subtraction Assignment
  • PHP Multiplication Assignment
  • PHP Division Assignment
  • PHP Modulus Assignment

In this PHP Tutorial , we learned about all the Assignment Operators in PHP programming, with examples.

Popular Courses by TutorialKart

App developement, web development, online tools.

PHP Tutorial

  • PHP Tutorial
  • PHP - Introduction
  • PHP - Installation
  • PHP - History
  • PHP - Features
  • PHP - Syntax
  • PHP - Hello World
  • PHP - Comments
  • PHP - Variables
  • PHP - Echo/Print
  • PHP - var_dump
  • PHP - $ and $$ Variables
  • PHP - Constants
  • PHP - Magic Constants
  • PHP - Data Types
  • PHP - Type Casting
  • PHP - Type Juggling
  • PHP - Strings
  • PHP - Boolean
  • PHP - Integers
  • PHP - Files & I/O
  • PHP - Maths Functions
  • PHP - Heredoc & Nowdoc
  • PHP - Compound Types
  • PHP - File Include
  • PHP - Date & Time
  • PHP - Scalar Type Declarations
  • PHP - Return Type Declarations
  • PHP Operators
  • PHP - Operators
  • PHP - Arithmatic Operators
  • PHP - Comparison Operators
  • PHP - Logical Operators
  • PHP - Assignment Operators
  • PHP - String Operators
  • PHP - Array Operators
  • PHP - Conditional Operators
  • PHP - Spread Operator
  • PHP - Null Coalescing Operator
  • PHP - Spaceship Operator
  • PHP Control Statements
  • PHP - Decision Making
  • PHP - If…Else Statement
  • PHP - Switch Statement
  • PHP - Loop Types
  • PHP - For Loop
  • PHP - Foreach Loop
  • PHP - While Loop
  • PHP - Do…While Loop
  • PHP - Break Statement
  • PHP - Continue Statement
  • PHP - Arrays
  • PHP - Indexed Array
  • PHP - Associative Array
  • PHP - Multidimensional Array
  • PHP - Array Functions
  • PHP - Constant Arrays
  • PHP Functions
  • PHP - Functions
  • PHP - Function Parameters
  • PHP - Call by value
  • PHP - Call by Reference
  • PHP - Default Arguments
  • PHP - Named Arguments
  • PHP - Variable Arguments
  • PHP - Returning Values
  • PHP - Passing Functions
  • PHP - Recursive Functions
  • PHP - Type Hints
  • PHP - Variable Scope
  • PHP - Strict Typing
  • PHP - Anonymous Functions
  • PHP - Arrow Functions
  • PHP - Variable Functions
  • PHP - Local Variables
  • PHP - Global Variables
  • PHP Superglobals
  • PHP - Superglobals
  • PHP - $GLOBALS
  • PHP - $_SERVER
  • PHP - $_REQUEST
  • PHP - $_POST
  • PHP - $_GET
  • PHP - $_FILES
  • PHP - $_ENV
  • PHP - $_COOKIE
  • PHP - $_SESSION
  • PHP File Handling
  • PHP - File Handling
  • PHP - Open File
  • PHP - Read File
  • PHP - Write File
  • PHP - File Existence
  • PHP - Download File
  • PHP - Copy File
  • PHP - Append File
  • PHP - Delete File
  • PHP - Handle CSV File
  • PHP - File Permissions
  • PHP - Create Directory
  • PHP - Listing Files
  • Object Oriented PHP
  • PHP - Object Oriented Programming
  • PHP - Classes and Objects
  • PHP - Constructor and Destructor
  • PHP - Access Modifiers
  • PHP - Inheritance
  • PHP - Class Constants
  • PHP - Abstract Classes
  • PHP - Interfaces
  • PHP - Traits
  • PHP - Static Methods
  • PHP - Static Properties
  • PHP - Namespaces
  • PHP - Object Iteration
  • PHP - Encapsulation
  • PHP - Final Keyword
  • PHP - Overloading
  • PHP - Cloning Objects
  • PHP - Anonymous Classes
  • PHP Web Development
  • PHP - Web Concepts
  • PHP - Form Handling
  • PHP - Form Validation
  • PHP - Form Email/URL
  • PHP - Complete Form
  • PHP - File Inclusion
  • PHP - GET & POST
  • PHP - File Uploading
  • PHP - Cookies
  • PHP - Sessions
  • PHP - Session Options
  • PHP - Sending Emails
  • PHP - Sanitize Input
  • PHP - Post-Redirect-Get (PRG)
  • PHP - Flash Messages
  • PHP - AJAX Introduction
  • PHP - AJAX Search
  • PHP - AJAX XML Parser
  • PHP - AJAX Auto Complete Search
  • PHP - AJAX RSS Feed Example
  • PHP - XML Introduction
  • PHP - Simple XML Parser
  • PHP - SAX Parser Example
  • PHP - DOM Parser Example
  • PHP Login Example
  • PHP - Login Example
  • PHP - Facebook and Paypal Integration
  • PHP - Facebook Login
  • PHP - Paypal Integration
  • PHP - MySQL Login
  • PHP Advanced
  • PHP - MySQL
  • PHP.INI File Configuration
  • PHP - Array Destructuring
  • PHP - Coding Standard
  • PHP - Regular Expression
  • PHP - Error Handling
  • PHP - Try…Catch
  • PHP - Bugs Debugging
  • PHP - For C Developers
  • PHP - For PERL Developers
  • PHP - Frameworks
  • PHP - Core PHP vs Frame Works
  • PHP - Design Patterns
  • PHP - Filters
  • PHP - Callbacks
  • PHP - Exceptions
  • PHP - Special Types
  • PHP - Hashing
  • PHP - Encryption
  • PHP - is_null() Function
  • PHP - System Calls
  • PHP - HTTP Authentication
  • PHP - Swapping Variables
  • PHP - Closure::call()
  • PHP - Filtered unserialize()
  • PHP - IntlChar
  • PHP - CSPRNG
  • PHP - Expectations
  • PHP - Use Statement
  • PHP - Integer Division
  • PHP - Deprecated Features
  • PHP - Removed Extensions & SAPIs
  • PHP - FastCGI Process
  • PHP - PDO Extension
  • PHP - Built-In Functions
  • PHP Useful Resources
  • PHP - Questions & Answers
  • PHP - Quick Guide
  • PHP - Useful Resources
  • PHP - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

PHP - Assignment Operators Examples

You can use assignment operators in PHP to assign values to variables. Assignment operators are shorthand notations to perform arithmetic or other operations while assigning a value to a variable. For instance, the "=" operator assigns the value on the right-hand side to the variable on the left-hand side.

Additionally, there are compound assignment operators like +=, -= , *=, /=, and %= which combine arithmetic operations with assignment. For example, "$x += 5" is a shorthand for "$x = $x + 5", incrementing the value of $x by 5. Assignment operators offer a concise way to update variables based on their current values.

The following table highligts the assignment operators that are supported by PHP −

Operator Description Example
= Simple assignment operator. Assigns values from right side operands to left side operand C = A + B will assign value of A + B into C
+= Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand C += A is equivalent to C = C + A
-= Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand C -= A is equivalent to C = C - A
*= Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand C *= A is equivalent to C = C * A
/= Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand C /= A is equivalent to C = C / A
%= Modulus AND assignment operator. It takes modulus using two operands and assign the result to left operand C %= A is equivalent to C = C % A

The following example shows how you can use these assignment operators in PHP −

It will produce the following output −

PHP Assignment Operators

Php tutorial index.

PHP assignment operators applied to assign the result of an expression to a variable. = is a fundamental assignment operator in PHP. It means that the left operand gets set to the value of the assignment expression on the right.

Operator Description
= Assign
+= Increments then assigns
-= Decrements then assigns
*= Multiplies then assigns
/= Divides then assigns
%= Modulus then assigns

The PHP Handbook – Learn PHP for Beginners

Flavio Copes

PHP is an incredibly popular programming language.

Statistics say it’s used by 80% of all websites. It’s the language that powers WordPress, the widely used content management system for websites.

And it also powers a lot of different frameworks that make Web Development easier, like Laravel. Speaking of Laravel, it may be one of the most compelling reasons to learn PHP these days.

Why Learn PHP?

PHP is quite a polarizing language. Some people love it, and some people hate it. If we move a step above the emotions and look at the language as a tool, PHP has a lot to offer.

Sure it’s not perfect. But let me tell you – no language is.

In this handbook, I’m going to help you learn PHP.

This book is a perfect introduction if you’re new to the language. It’s also perfect if you’ve done “some PHP” in the past and you want to get back to it.

I’ll explain modern PHP, version 8+.

PHP has evolved a lot in the last few years. So if the last time you tried it was PHP 5 or even PHP 4, you’ll be surprised at all the good things that PHP now offers.

Here's what we'll cover in this handbook:

Introduction to PHP

What kind of language is php, how to setup php, how to code your first php program, php language basics, how to work with strings in php, how to use built-in functions for numbers in php, how arrays work in php, how conditionals work in php, how loops work in php, how functions work in php, how to loop through arrays with map() , filter() , and reduce() in php, object oriented programming in php, how to include other php files, useful constants, functions and variables for filesystem in php, how to handle errors in php, how to handle exceptions in php, how to work with dates in php, how to use constants and enums in php, how to use php as a web app development platform, how to use composer and packagist, how to deploy a php application.

Note that you can get a PDF, ePub, or Mobi version of this handbook for easier reference, or for reading on your Kindle or tablet.

PHP is a programming language that many devs use to create Web Applications, among other things.

As a language, it had a humble beginning. It was first created in 1994 by Rasmus Lerdorf to build his personal website. He didn’t know at the time it would eventually become one of the most popular programming languages in the world. It became popular later on, in 1997/8, and exploded in the 2000s when PHP 4 landed.

You can use PHP to add a little interactivity to an HTML page.

Or you can use it as a Web Application engine that creates HTML pages dynamically and sends them to the browser.

It can scale to millions of page views.

Did you know Facebook is powered by PHP? Ever heard of Wikipedia? Slack? Etsy?

Let’s get into some technical jargon.

Programming languages are divided into groups depending on their characteristics. For example interpreted/compiled, strongly/loosely typed, dynamically/statically typed.

PHP is often called a “scripting language” and it’s an interpreted language . If you’ve used compiled languages like C or Go or Swift, the main difference is that you don’t need to compile a PHP program before you run it.

Those languages are compiled and the compiler generates an executable program that you then run. It’s a 2-steps process.

The PHP interpreter is responsible for interpreting the instructions written in a PHP program when it’s executed. It’s just one step. You tell the interpreter to run the program. It's a completely different workflow.

PHP is a dynamically typed language . The types of variables are checked at runtime, rather than before the code is executed as happens for statically typed languages. (These also happen to be compiled – the two characteristics often go hand in hand.)

PHP is also loosely (weakly) typed. Compared to strongly typed languages like Swift, Go, C or Java, you don’t need to declare the types of your variables.

Being interpreted and loosely/dynamically typed will make bugs harder to find before they happen at runtime.

In compiled languages, you can often catch errors at compile time, something that does not happen in interpreted languages.

But on the other hand, an interpreted language has more flexibility.

Fun fact: PHP is written internally in C, a compiled and statically typed language.

In its nature, PHP is similar to JavaScript, another dynamically typed, loosely typed, and interpreted language.

PHP supports object-oriented programming, and also functional programming. You can use it as you prefer.

There are many ways to install PHP on your local machine.

The most convenient way I’ve found to install PHP locally is to use MAMP.

MAMP is a tool that’s freely available for all the Operating Systems – Mac, Windows and Linux. It is a package that gives you all the tools you need to get up and running.

PHP is run by a HTTP Server, which is responsible for responding to HTTP requests, the ones made by the browser. So you access a URL with your browser, Chrome or Firefox or Safari, and the HTTP server responds with some HTML content.

The server is typically Apache or NGINX.

Then to do anything non-trivial you’ll need a database, like MySQL.

MAMP is a package that provides all of that, and more, and gives you a nice interface to start/stop everything at once.

Of course, you can set up each piece on its own if you like, and many tutorials explain how to do that. But I like simple and practical tools, and MAMP is one of those.

You can follow this handbook with any kind of PHP installation method, not just MAMP.

That said, if you don’t have PHP installed yet and you want to use MAMP, go to https://www.mamp.info and install it.

The process will depend on your operating system, but once you’re done with the installation, you will have a “MAMP” application installed.

Start that, and you will see a window similar to this:

Screen Shot 2022-06-24 at 15.14.05.jpg

Make sure the PHP version selected is the latest available.

At the time of writing MAMP lets you pick 8.0.8.

NOTE: I noticed MAMP has a version that’s a bit behind, not the latest. You can install a more recent version of PHP by enabling the MAMP PRO Demo, then install the latest release from the MAMP PRO settings (in my case it was 8.1.0). Then close it and reopen MAMP (non-pro version). MAMP PRO has more features so you might want to use it, but it’s not necessary to follow this handbook.

Press the Start button at the top right. This will start the Apache HTTP server, with PHP enabled, and the MySQL database.

Go to the URL http://localhost:8888 and you will see a page similar to this:

Screen Shot 2022-06-24 at 15.19.05.jpg

We’re ready to write some PHP!

Open the folder listed as “Document root”. If you're using MAMP on a Mac it’s by default /Applications/MAMP/htdocs .

On Windows it’s C:\MAMP\htdocs .

Yours might be different depending on your configuration. Using MAMP you can find it in the user interface of the application.

In there, you will find a file named index.php .

That is responsible for printing the page shown above.

Screen Shot 2022-06-24 at 15.17.58.jpg

When learning a new programming language we have this tradition of creating a “Hello, World!” application. Something that prints those strings.

Make sure MAMP is running, and open the htdocs folder as explained above.

Open the index.php file in a code editor.

I recommend using VS Code , as it’s a very simple and powerful code editor. You can check out https://flaviocopes.com/vscode/ for an introduction.

Screen Shot 2022-06-24 at 15.37.36.jpg

This is the code that generates the “Welcome to MAMP” page you saw in the browser.

Delete everything and replace it with:

Save, refresh the page on http://localhost:8888 , you should see this:

Screen Shot 2022-06-24 at 15.39.00.jpg

Great! That was your first PHP program.

Let’s explain what is happening here.

We have the Apache HTTP server listening on port 8888 on localhost, your computer.

When we access http://localhost:8888 with the browser, we’re making an HTTP request, asking for the content of the route / , the base URL.

Apache, by default, is configured to serve that route serving the index.html file included in the htdocs folder. That file does not exist – but as we have configured Apache to work with PHP, it will then search for an index.php file.

This file exists, and PHP code is executed server-side before Apache sends the page back to the browser.

In the PHP file, we have a <?php opening, which says “here starts some PHP code”.

We have an ending ?> that closes the PHP code snippet, and inside it, we use the echo instruction to print the string enclosed into quotes into the HTML.

A semicolon is required at the end of every statement.

We have this opening/closing structure because we can embed PHP inside HTML. PHP is a scripting language, and its goal is to be able to “decorate” an HTML page with dynamic data.

Note that with modern PHP, we generally avoid mixing PHP into the HTML. Instead, we use PHP as a “framework to generate the HTML” – for example using tools like Laravel. But we'll discuss plain PHP in this book, so it makes sense to start from the basics.

For example, something like this will give you the same result in the browser:

To the final user, who looks at the browser and has no idea of the code behind the scenes, there’s no difference at all.

The page is technically an HTML page, even though it does not contain HTML tags but just a Hello World string. But the browser can figure out how to display that in the window.

After the first “Hello World”, it’s time to dive into the language features with more details.

How Variables Work in PHP

Variables in PHP start with the dollar sign $ , followed by an identifier, which is a set of alphanumeric chars and the underscore _ char.

You can assign a variable any type of value, like strings (defined using single or double quotes):

Or numbers:

or any other type that PHP allows, as we’ll later see.

Once a variable is assigned a value, for example a string, we can reassign it a different type of value, like a number:

PHP won’t complain that now the type is different.

Variable names are case-sensitive. $name is different from $Name .

It’s not a hard rule, but generally variable names are written in camelCase format, like this: $brandOfCar or $ageOfDog . We keep the first letter lowercase, and the letters of the subsequent words uppercase.

How to Write Comments in PHP

A very important part of any programming language is how you write comments.

You write single-line comments in PHP in this way:

Multi-line comments are defined in this way:

What are Types in PHP?

I mentioned strings and numbers.

PHP has the following types:

  • bool boolean values (true/false)
  • int integer numbers (no decimals)
  • float floating-point numbers (decimals)
  • string strings
  • array arrays
  • object objects
  • null a value that means “no value assigned”

and a few other more advanced ones.

How to Print the Value of a Variable in PHP

We can use the var_dump() built-in function to get the value of a variable:

The var_dump($name) instruction will print string(6) "Flavio" to the page, which tells us the variable is a string of 6 characters.

If we used this code:

we’d have int(20) back, saying the value is 20 and it’s an integer.

var_dump() is one of the essential tools in your PHP debugging tool belt.

How Operators Work in PHP

Once you have a few variables you can make operations with them:

The * I used to multiply $base by $height is the multiplication operator.

We have quite a few operators – so let’s do a quick roundup of the main ones.

To start with, here are the arithmetic operators: + , - , * , / (division), % (remainder) and ** (exponential).

We have the assignment operator = , which we already used to assign a value to a variable.

Next up we have comparison operators, like < , > , <= , >= . Those work like they do in math.

== returns true if the two operands are equal.

=== returns true if the two operands are identical.

What’s the difference?

You’ll find it with experience, but for example:

We also have != to detect if operands are not equal:

and !== to detect if operands are not identical:

Logical operators work with boolean values:

We also have the not operator:

I used the boolean values true and false here, but in practice you’ll use expressions that evaluate to either true or false, for example:

All of the operators listed above are binary , meaning they involve 2 operands.

PHP also has 2 unary operators: ++ and -- :

I introduced the use of strings before when we talked about variables and we defined a string using this notation:

The big difference between using single and double quotes is that with double quotes we can expand variables in this way:

and with double quotes we can use escape characters (think new lines \n or tabs \t ):

PHP offers you a very comprehensive functions in its standard library (the library of functionalities that the language offers by default).

First, we can concatenate two strings using the . operator:

We can check the length of a string using the strlen() function:

This is the first time we've used a function.

A function is composed of an identifier ( strlen in this case) followed by parentheses. Inside those parentheses, we pass one or more arguments to the function. In this case, we have one argument.

The function does something and when it’s done it can return a value. In this case, it returns the number 6 . If there’s no value returned, the function returns null .

We’ll see how to define our own functions later.

We can get a portion of a string using substr() :

We can replace a portion of a string using str_replace() :

Of course we can assign the result to a new variable:

There are a lot more built-in functions you can use to work with strings.

Here is a brief non-comprehensive list just to show you the possibilities:

  • trim() strips white space at the beginning and end of a string
  • strtoupper() makes a string uppercase
  • strtolower() makes a string lowercase
  • ucfirst() makes the first character uppercase
  • strpos() finds the firsts occurrence of a substring in the string
  • explode() to split a string into an array
  • implode() to join array elements in a string

You can find a full list here .

I previously listed the few functions we commonly use for strings.

Let’s make a list of the functions we use with numbers:

  • round() to round a decimal number, up/down depending if the value is > 0.5 or smaller
  • ceil() to round a a decimal number up
  • floor() to round a decimal number down
  • rand() generates a random integer
  • min() finds the lowest number in the numbers passed as arguments
  • max() finds the highest number in the numbers passed as arguments
  • is_nan() returns true if the number is not a number

There are a ton of different functions for all sorts of math operations like sine, cosine, tangents, logarithms, and so on. You can find a full list here .

Arrays are lists of values grouped under a common name.

You can define an empty array in two different ways:

An array can be initialized with values:

Arrays can hold values of any type:

Even other arrays:

You can access the element in an array using this notation:

Once an array is created, you can append values to it in this way:

You can use array_unshift() to add the item at the beginning of the array instead:

Count how many items are in an array using the built-in count() function:

Check if an array contains an item using the in_array() built-in function:

If in addition to confirming existence, you need the index, use array_search() :

Useful Functions for Arrays in PHP

As with strings and numbers, PHP provides lots of very useful functions for arrays. We’ve seen count() , in_array() , array_search() – let’s see some more:

  • is_array() to check if a variable is an array
  • array_unique() to remove duplicate values from an array
  • array_search() to search a value in the array and return the key
  • array_reverse() to reverse an array
  • array_reduce() to reduce an array to a single value using a callback function
  • array_map() to apply a callback function to each item in the array. Typically used to create a new array by modifying the values of an existing array, without altering it.
  • array_filter() to filter an array to a single value using a callback function
  • max() to get the maximum value contained in the array
  • min() to get the minimum value contained in the array
  • array_rand() to get a random item from the array
  • array_count_values() to count all the values in the array
  • implode() to turn an array into a string
  • array_pop() to remove the last item of the array and return its value
  • array_shift() same as array_pop() but removes the first item instead of the last
  • sort() to sort an array
  • rsort() to sort an array in reverse order
  • array_walk() similarly to array_map() does something for every item in the array, but in addition it can change values in the existing array

How to Use Associative Arrays in PHP

So far we’ve used arrays with an incremental, numeric index: 0, 1, 2…

You can also use arrays with named indexes (keys), and we call them associative arrays:

We have some functions that are especially useful for associative arrays:

  • array_key_exists() to check if a key exists in the array
  • array_keys() to get all the keys from the array
  • array_values() to get all the values from the array
  • asort() to sort an associative array by value
  • arsort() to sort an associative array in descending order by value
  • ksort() to sort an associative array by key
  • krsort() to sort an associative array in descending order by key

You can see all array-related functions here .

I previously introduced comparison operators: < , > , <= , >= , == , === , != , !== ... and so on.

Those operators are going to be super useful for one thing: conditionals .

Conditionals are the first control structure we see.

We can decide to do something, or something else, based on a comparison.

For example:

The code inside the parentheses only executes if the condition evaluates to true .

Use else to do something else in case the condition is false :

NOTE: I used cannot instead of can't because the single quote would terminate my string before it should. In this case you could escape the ' in this way: echo 'You can\'t enter the pub';

You can have multiple if statements chained using elseif :

In addition to if , we have the switch statement.

We use this when we have a variable that could have a few different values, and we don’t have to have a long if / elseif block:

I know the example does not have any logic, but I think it can help you understand how switch works.

The break; statement after each case is essential. If you don’t add that and the age is 17, you’d see this:

Instead of just this:

as you’d expect.

Loops are another super useful control structure.

We have a few different kinds of loops in PHP: while , do while , for , and foreach .

Let’s see them all!

How to Use a while loop in PHP

A while loop is the simplest one. It keeps iterating while the condition evaluates to true :

This would be an infinite loop, which is why we use variables and comparisons:

How to Use a do while loop in PHP

do while is similar, but slightly different in how the first iteration is performed:

In the do while loop, first we do the first iteration, then we check the condition.

In the while loop, first we check the condition, then we do the iteration.

Do a simple test by setting $counter to 15 in the above examples, and see what happens.

You'll want to choose one kind of loop, or the other, depending on your use case.

How to Use a foreach Loop in PHP

You can use the foreach loop to easily iterate over an array:

You can also get the value of the index (or key in an associative array) in this way:

How to Use a for Loop in PHP

The for loop is similar to while, but instead of defining the variable used in the conditional before the loop, and instead of incrementing the index variable manually, it’s all done in the first line:

You can use the for loop to iterate over an array in this way:

How to Use the break and continue Statements in PHP

In many cases you want the ability to stop a loop on demand.

For example you want to stop a for loop when the value of the variable in the array is 'b' :

This makes the loop completely stop at that point, and the program execution continues at the next instruction after the loop.

If you just want to skip the current loop iteration and keep looking, use continue instead:

Functions are one of the most important concepts in programming.

You can use functions to group together multiple instructions or multiple lines of code, and give them a name.

For example you can make a function that sends an email. Let’s call it sendEmail , and we'll define it like this:

And you can call it anywhere else by using this syntax:

You can also pass arguments to a function. For example when you send an email, you want to send it to someone – so you add the email as the first argument:

Inside the function definition we get this parameter in this way (we call them parameters inside the function definition, and arguments when we call the function):

You can send multiple arguments by separating them with commas:

And we can get those parameters in the order they were defined:

We can optionally set the type of parameters:

Parameters can have a default value, so if they are omitted we can still have a value for them:

A function can return a value. Only one value can be returned from a function, not more than one. You do that using the return keyword. If omitted, the function returns null .

The returned value is super useful as it tells you the result of the work done in the function, and lets you use its result after calling it:

We can optionally set the return type of a function using this syntax:

When you define a variable inside a function, that variable is local to the function, which means it’s not visible from outside. When the function ends, it just stops existing:

Variables defined outside of the function are not accessible inside the function.

This enforces a good programming practice as we can be sure the function does not modify external variables and cause “side effects”.

Instead you return a value from the function, and the outside code that calls the function will take responsibility for updating the outside variable.

You can pass the value of a variable by passing it as an argument to the function:

But you can’t modify that value from within the function.

It’s passed by value , which means the function receives a copy of it, not the reference to the original variable.

That is still possible using this syntax (notice I used & in the parameter definition):

The functions we've defined so far are named functions .

They have a name.

We also have anonymous functions , which can be useful in a lot of cases.

They don’t have a name, per se, but they are assigned to a variable. To call them, you invoke the variable with parentheses at the end:

Note that you need a semicolon after the function definition, but then they work like named functions for return values and parameters.

Interestingly, they offer a way to access a variable defined outside the function through use() :

Another kind of function is an arrow function .

An arrow function is an anonymous function that’s just one expression (one line), and implicitly returns the value of that expression.

You define it in this way:

Here’s an example:

You can pass parameters to an arrow function:

Note that as the next example shows, arrow functions have automatic access to the variables of the enclosing scope, without the need of use() .

Arrow functions are super useful when you need to pass a callback function. We’ll see how to use them to perform some array operations later.

So we have in total 3 kinds of functions: named functions , anonymous functions , and arrow functions .

Each of them has its place, and you’ll learn how to use them properly over time, with practice.

Another important set of looping structures, often used in functional programming, is the set of array_map() / array_filter() / array_reduce() .

Those 3 built-in PHP functions take an array, and a callback function that in each iteration takes each item in the array.

array_map() returns a new array that contains the result of running the callback function on each item in the array:

array_filter() generates a new array by only getting the items whose callback function returns true :

array_reduce() is used to reduce an array to a single value.

For example we can use it to multiply all items in an array:

Notice the last parameter – it’s the initial value. If you omit that, the default value is 0 but that would not work for our multiplication example.

Note that in array_map() the order of the arguments is reversed. First you have the callback function and then the array. This is because we can pass multiple arrays using commas ( array_map(fn($value) => $value * 2, $numbers, $otherNumbers, $anotherArray); ). Ideally we’d like more consistency, but that’s what it is.

Let’s now jump head first into a big topic: object-oriented programming with PHP.

Object-oriented programming lets you create useful abstractions and make your code simpler to understand and manage.

How to Use Classes and Objects in PHP

To start with, you have classes and objects.

A class is a blueprint, or type, of object.

For example you have the class Dog , defined in this way:

Note that the class must be defined in uppercase.

Then you can create objects from this class – specific, individual dogs.

An object is assigned to a variable, and it’s instantiated using the new Classname() syntax:

You can create multiple objects from the same class, by assigning each object to a different variable:

How to Use Properties in PHP

Those objects will all share the same characteristics defined by the class. But once they are instantiated, they will have a life of their own.

For example, a Dog has a name, an age, and a fur color.

So we can define those as properties in the class:

They work like variables, but they are attached to the object, once it's instantiated from the class. The public keyword is the access modifier and sets the property to be publicly accessible.

You can assign values to those properties in this way:

Notice that the property is defined as public .

That is called an access modifier. You can use two other kinds of access modifiers: private and protected . Private makes the property inaccessible from outside the object. Only methods defined inside the object can access it.

We’ll see more about protected when we’ll talk about inheritance.

How to Use Methods in PHP

Did I say method? What is a method?

A method is a function defined inside the class, and it’s defined in this way:

Methods are very useful to attach a behavior to an object. In this case we can make a dog bark.

Notice that I use the public keyword. That’s to say that you can invoke a method from outside the class. Like for properties, you can mark methods as private too, or protected , to restrict their access.

You invoke a method on the object instance like this:

A method, just like a function, can define parameters and a return value, too.

Inside a method we can access the object’s properties using the special built-in $this variable, which, when referenced inside a method, points to the current object instance:

Notice I used $this->name to set and access the $name property, and not $this->$name .

How to Use the Constructor Method in PHP

A special kind of method named __construct() is called a constructor .

You use this method to initialize the properties of an object when you create it, as it’s automatically invoked when calling new Classname() .

This is such a common thing that PHP (starting in PHP 8) includes something called constructor promotion where it automatically does this thing:

By using the access modifier, the assignment from the parameter of the constructor to the local variable happens automatically:

Properties can be typed .

You can require the name to be a string using public string $name :

Now all works fine in this example, but try changing that to public int $name to require it to be an integer.

PHP will raise an error if you initialize $name with a string:

Interesting, right?

We can enforce properties to have a specific type between string , int , float , string , object , array , bool and others .

What is Inheritance in PHP?

The fun in object oriented programming starts when we allow classes to inherit properties and methods from other classes.

Suppose you have an Animal class:

Every animal has an age, and every animal can eat. So we add an age property and an eat() method:

A dog is an animal and has an age and can eat too, so the Dog class – instead of reimplementing the same things we have in Animal – can extend that class:

We can now instantiate a new object of class Dog and we have access to the properties and methods defined in Animal :

In this case we call Dog the child class and Animal the parent class .

Inside the child class we can use $this to reference any property or method defined in the parent, as if they were defined inside the child class.

It’s worth noting that while we can access the parent’s properties and methods from the child, we can’t do the reverse.

The parent class knows nothing about the child class.

protected Properties and Methods in PHP

Now that we've introduced inheritance, we can discuss protected . We already saw how we can use the public access modifier to set properties and methods callable from outside of a class, by the public.

private properties and methods can only be accessed from within the class.

protected properties and methods can be accessed from within the class and from child classes.

How to Override Methods in PHP

What happens if we have an eat() method in Animal and we want to customize it in Dog ? We can override that method.

Now any instance of Dog will use the Dog 's implementation of the eat() method.

Static Properties and Methods in PHP

We’ve seen how to define properties and methods that belong to the instance of a class , an object.

Sometimes it’s useful to assign those to the class itself.

When this happens we call them static , and to reference or call them we don’t need to create an object from the class.

Let’s start with static properties. We define them with the static keyword:

We reference them from inside the class using the keyword self , which points to the class:

and from outside the class using:

This is what happens for static methods:

From the outside of the class we can call them in this way:

From inside the class, we can reference them using the self keyword, which refers to the current class:

How to Compare Objects in PHP

When we talked about operators I mentioned we have the == operator to check if two values are equal and === to check if they are identical.

Mainly the difference is that == checks the object content, for example the '5' string is equal to the number 5 , but it’s not identical to it.

When we use those operators to compare objects, == will check if the two objects have the same class and have the same values assigned to them.

=== on the other hand will check if they also refer to the same instance (object).

How to Iterate over Object Properties in PHP

You can loop over all the public properties in an object using a foreach loop, like this:

How to Clone Objects in PHP

When you have an object, you can clone it using the clone keyword:

This performs a shallow clone , which means that references to other variables will be copied as references – there will not a “recursive cloning” of them.

To do a deep clone you will need to do some more work.

What are Magic Methods in PHP?

Magic methods are special methods that we define in classes to perform some behavior when something special happens.

For example when a property is set, or accessed, or when the object is cloned.

We’ve seen __construct() before.

That’s a magic method.

There are others. For example we can set a “cloned” boolean property to true when the object is cloned:

Other magic methods include __call() , __get() , __set() , __isset() , __toString() and others.

You can see the full list here

We’re now done talking about the object oriented features of PHP.

Let’s now explore some other interesting topics!

Inside a PHP file you can include other PHP files. We have the following methods, all used for this use case, but they're all slightly different: include , include_once , require , and require_once .

include loads the content of another PHP file, using a relative path.

require does the same, but if there’s any error doing so, the program halts. include will only generate a warning.

You can decide to use one or the other depending on your use case. If you want your program to exit if it can’t import the file, use require .

include_once and require_once do the same thing as their corresponding functions without _once , but they make sure the file is included/required only once during the execution of the program.

This is useful if, for example, you have multiple files loading some other file, and you typically want to avoid loading that more than once.

My rule of thumb is to never use include or require because you might load the same file twice. include_once and require_once help you avoid this problem.

Use include_once when you want to conditionally load a file, for example “load this file instead of that”. In all other cases, use require_once .

The above syntax includes the test.php file from the current folder, the file where this code is.

You can use relative paths:

to include a file in the parent folder or to go in a subfolder:

You can use absolute paths:

In modern PHP codebases that use a framework, files are generally loaded automatically so you’ll have less need to use the above functions.

Speaking of paths, PHP offers you several utilities to help you work with paths.

You can get the full path of the current file using:

  • __FILE__ , a magic constant
  • $_SERVER['SCRIPT_FILENAME'] (more on $_SERVER later!)

You can get the full path of the folder where the current file is using:

  • the getcwd() built-in function
  • __DIR__ , another magic constant
  • combine __FILE__ with dirname() to get the current folder full path: dirname(__FILE__)
  • use $_SERVER['DOCUMENT_ROOT']

Every programmer makes errors. We’re humans, after all.

We might forget a semicolon. Or use the wrong variable name. Or pass the wrong argument to a function.

In PHP we have:

The first two are minor errors, and they do not stop the program execution. PHP will print a message, and that’s it.

Errors terminate the execution of the program, and will print a message telling you why.

There are many different kinds of errors, like parse errors, runtime fatal errors, startup fatal errors, and more.

They’re all errors.

I said “PHP will print a message”, but.. where?

This depends on your configuration.

In development mode it’s common to log PHP errors directly into the Web page, but also in an error log.

You want to see those errors as early as possible, so you can fix them.

In production, on the other hand, you don’t want to show them in the Web page, but you still want to know about them.

So what do you do? You log them to the error log.

This is all decided in the PHP configuration.

We haven’t talked about this yet, but there’s a file in your server configuration that decides a lot of things about how PHP runs.

It’s called php.ini .

The exact location of this file depends on your setup.

To find out where is yours, the easiest way is to add this to a PHP file and run it in your browser:

You will then see the location under “Loaded Configuration File”:

Screen Shot 2022-06-27 at 13.42.41.jpg

In my case it’s /Applications/MAMP/bin/php/php8.1.0/conf/php.ini .

Note that the information generated by phpinfo() contains a lot of other useful information. Remember that.

Using MAMP you can open the MAMP application folder and open bin/php . Go in your specific PHP version (8.1.0 in my case) then go in conf . In there you’ll find the php.ini file:

Screen Shot 2022-06-27 at 12.11.28.jpg

Open that file in an editor.

It contains a really long list of settings, with a great inline documentation for each one.

We’re particularly interested in display_errors :

Screen Shot 2022-06-27 at 12.13.16.jpg

In production you want its value to be Off , as the docs above it say.

The errors will not show up anymore in the website, but you will see them in the php_error.log file in the logs folder of MAMP in this case:

Screen Shot 2022-06-27 at 12.16.01.jpg

This file will be in a different folder depending on your setup.

You set this location in your php.ini :

Screen Shot 2022-06-27 at 12.17.12.jpg

The error log will contain all the error messages your application generates:

Screen Shot 2022-06-27 at 12.17.55.jpg

You can add information to the error log by using the error_log() function:

It’s common to use a logger service for errors, like Monolog .

Sometimes errors are unavoidable. Like if something completely unpredictable happens.

But many times, we can think ahead, and write code that can intercept an error, and do something sensible when this happens. Like showing a useful error message to the user, or trying a workaround.

We do so using exceptions .

Exceptions are used to make us, developers, aware of a problem.

We wrap some code that can potentially raise an exception into a try block, and we have a catch block right after that. That catch block will be executed if there’s an exception in the try block:

Notice that we have an Exception object $e being passed to the catch block, and we can inspect that object to get more information about the exception, like this:

Let’s look at an example.

Let's say that by mistake I divide a number by zero:

This will trigger a fatal error and the program is halted on that line:

Screen Shot 2022-06-26 at 20.12.59.jpg

Wrapping the operation in a try block and printing the error message in the catch block, the program ends successfully, telling me the problem:

Screen Shot 2022-06-26 at 20.13.36.jpg

Of course this is a simple example but you can see the benefit: I can intercept the issue.

Each exception has a different class. For example we can catch this as DivisionByZeroError and this lets me filter the possible problems and handle them differently.

I can have a catch-all for any throwable error at the end, like this:

Screen Shot 2022-06-26 at 20.15.47.jpg

And I can also append a finally {} block at the end of this try/catch structure to execute some code after the code is either executed successfully without problems, or there was a catch :

Screen Shot 2022-06-26 at 20.17.33.jpg

You can use the built-in exceptions provided by PHP but you can also create your own exceptions.

Working with dates and times is very common in programming. Let’s see what PHP provides.

We can get the current timestamp (number of seconds since Jan 1 1970 00:00:00 GMT) using time() :

When you have a timestamp you can format that as a date using date() , in the format you prefer:

Y is the 4-digit representation of the year, m is the month number (with a leading zero) and d is the number of the day of the month, with a leading zero.

See the full list of characters you can use to format the date here .

We can convert any date into a timestamp using strtotime() , which takes a string with a textual representation of a date and converts it into the number of seconds since Jan 1 1970:

...it’s pretty flexible.

For dates, it’s common to use libraries that offer a lot more functionality than what the language can. A good option is Carbon .

We can define constants in PHP using the define() built-in function:

And then we can use TEST as if it was a variable, but without the $ sign:

We use uppercase identifiers as a convention for constants.

Interestingly, inside classes we can define constant properties using the const keyword:

By default they are public but we can mark them as private or protected :

Enums allow you to group constants under a common “root”. For example you want to have a Status enum that has 3 states: EATING SLEEPING RUNNING , the 3 states of a dog’s day.

So you have:

Now we can reference those constants in this way:

Enums are objects, they can have methods and lots more features than we can get into here in this short introduction.

PHP is a server-side language and it is typically used in two ways.

One is within an HTML page, so PHP is used to “add” stuff to the HTML which is manually defined in the .php file. This is a perfectly fine way to use PHP.

Another way considers PHP more like the engine that is responsible for generating an “application”. You don't write the HTML in a .php file, but instead you use a templating language to generate the HTML, and everything is managed by what we call the framework .

This is what happens when you use a modern framework like Laravel.

I would consider the first way a bit “out of fashion” these days, and if you’re just starting out you should know about those two different styles of using PHP.

But also consider using a framework like “easy mode” because frameworks give you tools to handle routing, tools to access data from a database, and they make it easier to build a more secure application. And they make it all faster to develop.

That said, we’re not going to talk about using frameworks in this handbook. But I will talk about the basic, fundamental building blocks of PHP. They are essentials that any PHP developer must know.

Just know that “in the real world” you might use your favorite framework’s way of doing things rather than the lower level features offered by PHP.

This does not apply just to PHP of course – it’s an “issue” that happens with any programming language.

How to Handle HTTP Requests in PHP

Let’s start with handling HTTP requests.

PHP offers file-based routing by default. You create an index.php file and that responds on the / path.

We saw that when we made the Hello World example in the beginning.

Similarly, you can create a test.php file and automatically that will be the file that Apache serves on the /test route.

How to Use $_GET , $_POST and $_REQUEST in PHP

Files respond to all HTTP requests, including GET, POST and other verbs.

For any request you can access all the query string data using the $_GET object. It's called superglobal and is automatically available in all our PHP files.

This is of course most useful in GET requests, but also other requests can send data as a query string.

For POST, PUT and DELETE requests you’re more likely to need the data posted as URL-encoded data or using the FormData object, which PHP makes available to you using $_POST .

There is also $_REQUEST which contains all of $_GET and $_POST combined in a single variable.

How to Use the $_SERVER Object in PHP

We also have the superglobal variable $_SERVER , which you use to get a lot of useful information.

You saw how to use phpinfo() before. Let’s use it again to see what $_SERVER offers us.

In your index.php file in the root of MAMP run:

Then generate the page at localhost:8888 and search $_SERVER . You will see all the configuration stored and the values assigned:

Screen Shot 2022-06-27 at 13.46.50.jpg

Important ones you might use are:

  • $_SERVER['HTTP_HOST']
  • $_SERVER['HTTP_USER_AGENT']
  • $_SERVER['SERVER_NAME']
  • $_SERVER['SERVER_ADDR']
  • $_SERVER['SERVER_PORT']
  • $_SERVER['DOCUMENT_ROOT']
  • $_SERVER['REQUEST_URI']
  • $_SERVER['SCRIPT_NAME']
  • $_SERVER['REMOTE_ADDR']

How to Use Forms in PHP

Forms are the way the Web platform allows users to interact with a page and send data to the server.

Here is a simple form in HTML:

You can put this in your index.php file like it was called index.html .

A PHP file assumes you write HTML in it with some “PHP sprinkles” using <?php ?> so the Web Server can post that to the client. Sometimes the PHP part takes all of the page, and that’s when you generate all the HTML via PHP – it’s kind of the opposite of the approach we're taking here now.

So we have this index.php file that generates this form using plain HTML:

Screen Shot 2022-06-27 at 13.53.47.jpg

Pressing the Submit button will make a GET request to the same URL sending the data via query string. Notice that the URL changed to localhost:8888/?name=test .

Screen Shot 2022-06-27 at 13.56.46.jpg

We can add some code to check if that parameter is set using the isset() function:

Screen Shot 2022-06-27 at 13.56.35.jpg

See? We can get the information from the GET request query string through $_GET .

What you usually do with forms, though is you perform a POST request:

See, now we got the same information but the URL didn’t change. The form information was not appended to the URL.

Screen Shot 2022-06-27 at 13.59.54.jpg

This is because we’re using a POST request , which sends the data to the server in a different way, through URL-encoded data.

As mentioned above, PHP will still serve the index.php file as we’re still sending data to the same URL the form is on.

We’re mixing a bunch of code and we could separate the form request handler from the code that generates the form.

So we can have this in index.php :

and we can create a new post.php file with:

PHP will display this content now after we submit the form, because we set the action HTML attribute on the form.

This example is very simple, but the post.php file is where we could, for example, save the data to the database, or to a file.

How to Use HTTP Headers in PHP

PHP lets us set the HTTP headers of a response through the header() function.

HTTP Headers are a way to send information back to the browser.

We can say the page generates a 500 Internal Server Error:

Now you should see the status if you access the page with the Browser Developer Tools open:

Screen Shot 2022-06-27 at 14.10.29.jpg

We can set the content/type of a response:

We can force a 301 redirect:

We can use headers to say to the browser “cache this page”, “don’t cache this page”, and a lot more.

How to Use Cookies in PHP

Cookies are a browser feature.

When we send a response to the browser, we can set a cookie which will be stored by the browser, client-side.

Then, every request the browser makes will include the cookie back to us.

We can do many things with cookies. They are mostly used to create a personalized experience without you having to login to a service.

It’s important to note that cookies are domain-specific, so we can only read cookies we set on the current domain of our application, not other application’s cookies.

But JavaScript can read cookies (unless they are HttpOnly cookies but we’re starting to go into a rabbit hole) so cookies should not store any sensitive information.

We can use PHP to read the value of a cookie referencing the $_COOKIE superglobal:

The setcookie() function allows you to set a cookie:

We can add a third parameter to say when the cookie will expire. If omitted, the cookie expires at the end of the session/when the browser is closed.

Use this code to make the cookie expire in 7 days:

We can only store a limited amount of data in a cookie, and users can clear the cookies client-side when they clear the browser data.

Also, they are specific to the browser / device, so we can set a cookie in the user’s browser, but if they change browser or device, the cookie will not be available.

Let’s do a simple example with the form we used before. We’re going to store the name entered as a cookie:

I added some conditionals to handle the case where the cookie was already set, and to display the name right after the form is submitted, when the cookie is not set yet (it will only be set for the next HTTP request).

If you open the Browser Developer Tools you should see the cookie in the Storage tab.

From there you can inspect its value, and delete it if you want.

Screen Shot 2022-06-27 at 14.46.09.jpg

How to Use Cookie-based Sessions in PHP

One very interesting use case for cookies is cookie-based sessions.

PHP offers us a very easy way to create a cookie-based session using session_start() .

Try adding this:

in a PHP file, and load it in the browser.

You will see a new cookie named by default PHPSESSID with a value assigned.

That’s the session ID. This will be sent for every new request and PHP will use that to identify the session.

Screen Shot 2022-06-27 at 14.51.53.jpg

Similarly to how we used cookies, we can now use $_SESSION to store the information sent by the user – but this time it’s not stored client-side.

Only the session ID is.

The data is stored server-side by PHP.

Screen Shot 2022-06-27 at 14.53.24.jpg

This works for simple use cases, but of course for intensive data you will need a database.

To clear the session data you can call session_unset() .

To clear the session cookie use:

How to Work with Files and Folders in PHP

PHP is a server-side language, and one of the handy things it provides is access to the filesystem.

You can check if a file exists using file_exists() :

Get the size of a file using filesize() :

You can open a file using fopen() . Here we open the test.txt file in read-only mode and we get what we call a file descriptor in $file :

We can terminate the file access by calling fclose($fd) .

Read the content of a file into a variable like this:

feof() checks that we haven’t reached the end of the file as fgets reads 5000 bytes at a time.

You can also read a file line by line using fgets() :

To write to a file you must first open it in write mode , then use fwrite() :

We can delete a file using unlink() :

Those are the basics, but of course there are more functions to work with files .

PHP and Databases

PHP offers various built-in libraries to work with databases, for example:

  • MySQL / MariaDB

I won't cover this in the handbook because I think this is a big topic and one that would also require you to learn SQL.

I am also tempted to say that if you need a database you should use a framework or ORM that would save you security issues with SQL injection. Laravel’s Eloquent is a great example.

How to Work with JSON in PHP

JSON is a portable data format we use to represent data and send data from client to server.

Here’s an example of a JSON representation of an object that contains a string and a number:

PHP offers us two utility functions to work with JSON:

  • json_encode() to encode a variable into JSON
  • json_decode() to decode a JSON string into a data type (object, array…)

How to Send Emails with PHP

One of the things that I like about PHP is the conveniences, like sending an email.

Send an email using mail() :

To send emails at scale we can’t rely on this solution, as these emails tend to reach the spam folder more often than not. But for quick testing this is just helpful.

Libraries like https://github.com/PHPMailer/PHPMailer will be super helpful for more solid needs, using an SMTP server.

Composer is the package manager of PHP.

It allows you to easily install packages into your projects.

Install it on your machine ( Linux/Mac or Windows ) and once you’re done you should have a composer command available on your terminal.

Screen Shot 2022-06-27 at 16.25.43.jpg

Now inside your project you can run composer require <lib> and it will be installed locally. For example let's install the Carbon library that helps us work with dates in PHP

It will do some work:

Screen Shot 2022-06-27 at 16.27.11.jpg

Once it’s done, you will find some new things in the folder composer.json that lists the new configuration for the dependencies:

composer.lock is used to “lock” the versions of the package in time, so the exact same installation you have can be replicated on another server. The vendor folder contains the library just installed and its dependencies.

Now in the index.php file we can add this code at the top:

and then we can use the library!

Screen Shot 2022-06-27 at 16.34.47.jpg

See? We didn’t have to manually download a package from the internet and install it somewhere...it was all fast, quick, and well organized.

The require 'vendor/autoload.php'; line is what enables autoloading . Remember when we talked about require_once() and include_once() ? This solves all of that – we don’t need to manually search for the file to include, we just use the use keyword to import the library into our code.

When you’ve got an application ready, it’s time to deploy it and make it accessible from anyone on the Web.

PHP is the programming language with the best deployment story across the Web.

Trust me, every single other programming language and ecosystem wishes they were as easy as PHP.

The great thing about PHP, the thing it got right and allowed it to have the incredible success it has had, is the instant deploy.

You put a PHP file on a folder served by a Web server, and voilà – it just works.

No need to restart the server, run an executable, nothing.

This is still something that a lot of people do. You get a shared hosting for $3/month, upload your files via FTP, and you're done.

These days, though, I think Git deploy is something that should be baked into every project, and shared hosting should be a thing of the past.

One solution is always having your own private VPS (Virtual Private Server), which you can get from services like DigitalOcean or Linode.

But managing your own VPS is no joke. It requires serious knowledge and time investment, and constant maintenance.

You can also use the so-called PaaS (Platform as a Service), which are platforms that focus on taking care of all the boring stuff (managing servers) and you just upload your app and it runs.

Solutions like DigitalOcean App Platform (which is different from a DigitalOcean VPS), Heroku, and many others are great for your first tests.

These services allow you to connect your GitHub account and deploy any time you push a new change to your Git repository.

You can learn how to setup Git and GitHub from zero here .

This is a much better workflow compared to FTP uploads.

Let’s do a bare bones example.

I created a simple PHP application with just an index.php file:

I add the parent folder to my GitHub Desktop app, I initialize a Git repo, and I push it to GitHub:

Screen Shot 2022-06-27 at 17.26.24.jpg

Now go on digitalocean.com .

If you don’t have an account yet, use my referral code to sign up get $100 free credits over the next 60 days and you can work on your PHP app for free.

I connect to my DigitalOcean account and I go to Apps → Create App.

I connect my GitHub Account and select the repo of my app.

Make sure “Autodeploy” is checked, so the app will automatically redeploy on changes:

Screen Shot 2022-06-27 at 17.31.54.jpg

Click “Next” then Edit Plan:

Screen Shot 2022-06-27 at 17.32.24.jpg

By default the Pro plan is selected.

Use Basic and pick the $5/month plan.

Note that you pay $5 per month, but billing is per hour – so you can stop the app any time you want.

Screen Shot 2022-06-27 at 17.32.28.jpg

Then go back and press “Next” until the “Create Resources” button appears to create the app. You don’t need any database, otherwise that would be another $7/month on top.

Screen Shot 2022-06-27 at 17.33.46.jpg

Now wait until the deployment is ready:

Screen Shot 2022-06-27 at 17.35.00.jpg

The app is now up and running!

Screen Shot 2022-06-27 at 17.35.31.jpg

You’ve reached the end of the PHP Handbook!

Thank you for reading through this introduction to the wonderful world of PHP development. I hope it will help you get your web development job, become better at your craft, and empower you to work on your next big idea.

Note: you can get a PDF, ePub, or Mobi version of this handbook for easier reference, or for reading on your Kindle or tablet.

Read more posts .

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

  • ▼PHP Exercises
  • Introduction
  • Basic Algorithm
  • Exception Handling
  • File Handling
  • Cookies and Sessions
  • Object Oriented Programming
  • Regular Expression
  • Searching and Sorting
  • ▼PHP Challenges
  • Challenges-1
  • ..More to come..
  • PHP Exercises, Practice, Solution

What is PHP?

PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

The best way we learn anything is by practice and exercise questions. We have started this section for those (beginner to intermediate) who are familiar with PHP .

Hope, these exercises help you to improve your PHP coding skills. Currently, following sections are available, we are working hard to add more exercises. Happy Coding!

Note: It's fine if you are playing around with PHP codes with the help of an online PHP editor, to enjoy a full-fledged PHP environment (since online editors have several caveats, e.g. embedding PHP within HTML) up and running on your own machine is much better of an option to learn PHP. Please read our installing PHP on Windows and Linux if you are unfamiliar to PHP installation.

List of PHP Exercises :

  • PHP Basic : 102 Exercises with Solution
  • PHP Basic Algorithm: 136 Exercises with Solution
  • PHP Error and Exception Handling [ 10 exercises with solution ]
  • PHP File Handling [ 18 exercises with solution ]
  • PHP Cookies and Sessions Exercises Practice Solution [ 16 exercises with solution ]
  • PHP OOP Exercises Practice Solution [ 19 exercises with solution ]
  • PHP arrays : 59 Exercises with Solution
  • PHP for loop : 38 Exercises with Solution
  • PHP functions : 6 Exercises with Solution
  • PHP classes : 7 Exercises with Solution
  • PHP Regular Expression : 7 Exercises with Solution
  • PHP Date : 28 Exercises with Solution
  • PHP String : 26 Exercises with Solution
  • PHP Math : 12 Exercises with Solution
  • PHP JSON : 4 Exercises with Solution
  • PHP Searching and Sorting Algorithm : 17 Exercises with Solution
  • More to Come !

PHP Challenges :

  • PHP Challenges: Part -1 [ 1- 25]
  • More to come

Note : You may accomplish the same task (solution of the exercises) in various ways, therefore the ways described here are not the only ways to do stuff. Rather, it would be great, if this helps you anyway to choose your own methods.

[ Want to contribute to PHP exercises? Send your code (attached with a .zip file) to us at w3resource[at]yahoo[dot]com. Please avoid copyrighted materials.]

List of Exercises with Solutions :

  • HTML CSS Exercises, Practice, Solution
  • JavaScript Exercises, Practice, Solution
  • jQuery Exercises, Practice, Solution
  • jQuery-UI Exercises, Practice, Solution
  • CoffeeScript Exercises, Practice, Solution
  • Twitter Bootstrap Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution
  • C# Sharp Programming Exercises, Practice, Solution
  • Python Exercises, Practice, Solution
  • Java Exercises, Practice, Solution
  • SQL Exercises, Practice, Solution
  • MySQL Exercises, Practice, Solution
  • PostgreSQL Exercises, Practice, Solution
  • SQLite Exercises, Practice, Solution
  • MongoDB Exercises, Practice, Solution

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics

Learn PHP Variables

Print Cheatsheet

Parsing Variables within PHP Strings

In PHP, variables can be parsed within strings specified with double quotes ( " ).

This means that within the string, the computer will replace an occurence of a variable with that variable’s value.

When additional valid identifier characters (ie. characters that could be included in a variable name) are intended to appear adjacent to the variable’s value, the variable name can be wrapped in curly braces {} , thus avoiding confusion as to the variable’s name.

Reassignment of PHP Variables

In PHP, variables are assigned values with the assignment operator ( = ). The same variable can later be reassigned a new value using the same operator.

This process is known as reassignment .

Concatenating Strings in PHP

In PHP, if you want to join two strings together, you need to use the . operator.

This process is called concatenation . Put the . operator between the two strings in order to join them.

Note that strings are joined as-is, without inserting a whitespace character. So if you need to put spaces, you need to incorporate the whitespace manually within the string.

Appending a String in PHP

In PHP, there is a shortcut for appending a new string to the end of another string. This can be easily done with the string concatenation assignment operator ( .= ).

This operator will append the value on its right to the value on its left and then reassign the result to the variable on its left.

PHP Strings

In PHP, a string is a sequence of characters surrounded by double quotation marks. It can be as long as you want and contain any letters, numbers, symbols, and spaces.

PHP copying variables

In PHP, one variable’s value can be assigned to another variable.

This creates a copy of that variable’s value and assigns the new variable name to it.

Changes to the original variable will not affect the copy and changes to the copy will not affect the original. These variables are entirely separate entities.

PHP String Escape Sequences

In PHP, sometimes special characters must be escaped in order to include them in a string. Escape sequences start with a backslash character ( \ ).

There are a variety of escape sequences that can be used to accomplish different tasks. For example, to include a new line within a string, the sequence \n can be used. To include double quotation marks, the sequence \" can be used. Similarly, to include single quotes, the sequence \' can be used.

PHP Evaluation Order during Assignment

In PHP, when an assignment takes place, operations to the right of the assignment operator ( = ) will be evaluated to a single value first. The result of these operations will then be assigned to the variable.

PHP Variables

In PHP, variables are assigned values with the assignment operator ( = ).

Variable names can contain numbers, letters, and underscores ( _ ). A sigil ( $ ) must always precede a variable name. They cannot start with a number and they cannot have spaces or any special characters.

The convention in PHP is to use snake case for variable naming; this means that lowercase words are delimited with an underscore character ( _ ). Variable names are case-sensitive.

PHP Reference Assignment Operator

In PHP, the reference assignment operator ( =& ) is used to create a new variable as an alias to an existing spot in memory.

In other words, the reference assignment operator ( =& ) creates two variable names which point to the same value. So, changes to one variable will affect the other, without having to copy the existing data.

Integer Values in PHP

PHP supports integer values for numbers.

Integers are the set of all whole numbers, their negative counterparts, and zero. In other words, an integer is a number of the set ℤ = {…, -2, -1, 0, 1, 2, …}.

Exponentiation Operator in PHP

PHP supports an arithmetic operator for exponentiation ( ** ).

This operator gives the result of raising the value on the left to the power of the value on the right.

Arithmetic Operators in PHP

PHP supports arithmetic operators for addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ).

PHP operators will return integers whenever the result of an operation evaluates to a whole number. If the result evaluates to a fraction or decimal, then it will return a floating point number .

The Modulo Operator

PHP supports a modulo operator ( % ). The modulo operator returns the remainder of the left operand divided by the right operand. Operands of a modulo operation are converted to integers prior to performing the operation. The operation returns an integer with the same sign as the dividend.

Floating Point Numbers in PHP

PHP supports floating-point (decimal) numbers. They can be used to represent fractional quantities as well as precise measurements. Some examples of floating point numbers are 1.5 , 4.231 , 2.0 , etc.

CodedTag

  • Conditional Operators

Conditional Assignment Operator in PHP is a shorthand operator that allow developers to assign values to variables based on certain conditions.

In this article, we will explore how the various Conditional Assignment Operators in PHP simplify code and make it more readable.

Let’s begin with the ternary operator.

Ternary Operator Syntax

The Conditional Operator in PHP, also known as the Ternary Operator, assigns values to variables based on a certain condition. It takes three operands: the condition, the value to be assigned if the condition is true, and the value to be assigned if the condition is false.

Here’s an example:

In this example, the condition is $score >= 60 . If this condition is true, the value of $result is “Pass”. Otherwise, the value of $result is “Fail”.

To learn more, visit the PHP ternary operator tutorial . Let’s now explore the section below to delve into the Null Coalescing Operator in PHP.

The Null Coalescing Operator (??)

The Null Coalescing Operator, also known as the Null Coalescing Assignment Operator, assigns a default value to a variable if it is null. The operator has two operands: the variable and the default value it assigns if the variable is null. Here’s an example:

So, In this example, if the $_GET['name'] variable is null, the value of $name is “Guest”. Otherwise, the value of $name is the value of $_GET['name'] .

Here’s another pattern utilizing it with the assignment operator. Let’s proceed.

The Null Coalescing Assignment Operator (??=)

The Null Coalescing Operator with Assignment, also known as the Null Coalescing Assignment Operator, assigns a default value to a variable if it is null. The operator has two operands: the variable and the default value it assigns if the variable is null. Here’s an example:

So, the value of $name is null. The Null Coalescing Assignment Operator assigns the value “Guest” to $name. Therefore, the output of the echo statement is “Welcome,”Guest!”.

Moving into the following section, you’ll learn how to use the Elvis operator in PHP.

The Elvis Operator (?:)

In another hand, The Elvis Operator is a shorthand version of the Ternary Operator. Which assigns a default value to a variable if it is null. It takes two operands: the variable and the default value to be assigned if the variable is null. Here’s an example:

In this example, if the $_GET['name'] variable is null, the value“Guest” $name s “Guest”. Otherwise, the value of $name is the value of $_GET['name'] .

Let’s summarize it.

Wrapping Up

The Conditional Assignment Operators in PHP provide developers with powerful tools to simplify code and make it more readable. You can use these operators to assign values to variables based on certain conditions, assign default values to variables if they are null, and perform shorthand versions of conditional statements. By using these operators, developers can write more efficient and elegant code.

Did you find this article helpful?

 width=

Sorry about that. How can we improve it ?

  • Facebook -->
  • Twitter -->
  • Linked In -->
  • Install PHP
  • Hello World
  • PHP Constant
  • PHP Comments

PHP Functions

  • Parameters and Arguments
  • Anonymous Functions
  • Variable Function
  • Arrow Functions
  • Variadic Functions
  • Named Arguments
  • Callable Vs Callback
  • Variable Scope

Control Structures

  • If-else Block
  • Break Statement

PHP Operators

  • Operator Precedence
  • PHP Arithmetic Operators
  • Assignment Operators
  • PHP Bitwise Operators
  • PHP Comparison Operators
  • PHP Increment and Decrement Operator
  • PHP Logical Operators
  • PHP String Operators
  • Array Operators
  • Ternary Operator
  • PHP Enumerable
  • PHP NOT Operator
  • PHP OR Operator
  • PHP Spaceship Operator
  • AND Operator
  • Exclusive OR
  • Spread Operator
  • Null Coalescing Operator

Data Format and Types

  • PHP Data Types
  • PHP Type Juggling
  • PHP Type Casting
  • PHP strict_types
  • Type Hinting
  • PHP Boolean Type
  • PHP Iterable
  • PHP Resource
  • Associative Arrays
  • Multidimensional Array

String and Patterns

  • Remove the Last Char

PHPGurukul

Don't be Afraid of Source Code

PHP Projects

Online College Assignment System Using PHP and MySQL

by Anuj Kumar

Online College Assignment System
PHP5.6, PHP7.x
MySQL 5.x
HTML, AJAX,JQUERY,JAVASCRIPT
Mozilla, Google Chrome, IE8, OPERA
XAMPP / Wamp / Mamp/ Lamp (anyone)

In this project, we use PHP and   MySQL  database. It has three modules

  • User(Students)

Admin Module

  • Admin is the superuser of the website who can manage everything on the website. Admin can log in through the login page
  • Dashboard: In this section, admin can see all detail in brief like the total course, total subjects and total teachers.
  • Course: In this section, admin can mange course (add/update/delete).
  • Subject: In this section, admin can mange subject (add/update/delete).
  • Teacher: In this section, admin can manage teacher (add/update).
  • Announcement/News: In this section, admin can add and delete the announcement/news.
  • Uploaded Assignment: In this section, admin can view checked and unchecked assignment which is uploaded by the students and checked by teachers.
  • Search: In this section, admin can search uploaded assignment with the help of teacher name, assignment number and subjects name.
  • Reports: In this section, admin can view uploaded assignment report in a particular period.
  • Admin can also update his profile, change the password and recover the password.

Teacher Module

  • Dashboard: In this section, teacher can see all detail in brief like the total students (who is registered with the same course as the teacher have), total assignment and total announcement.
  • Assignment: In this section, teachers can manage the assignment (add/update).
  • Uploaded Assignment: In this section, teachers can view checked and unchecked assignment which is uploaded by the students and checked by them.
  • Subject Wise Reports: In this section, teacher can view uploaded assignment (subject wise) report in particular periods.
  • Reg Users(students): In this section, teacher can view the detail of registered students with particular courses.
  • Teacher can also view his profile, change the password and recover the password.

User Module

  • Dashboard: In this section, user(students) can view the notice which is announced by his/her course teachers.
  • Assignment: In this section, user(students) submit his/her own assignment and view assignment status it is checked or unchecked.
  • Teacher can also update his/her profile, change the password and recover the password.

Brief of Home Page

It is the home page of Online College Assignment System on this students can view notice which by announcing by a college administrator and also the unregistered student can register himself.

Some of the Project Screens

OCAS Home Page

User/ Student Signup

assignment with php

Teacher Dashboard

OCAS Teachers Dashboard

Teachers add Assignment

OCAS Add teachers Assignment.

How to run the Online College Assignment System Project Using PHP and MySQL

1.Download the zip file

2.Extract the file and copy ocas folder

3.Paste inside root directory(for xampp xampp/htdocs, for wamp wamp/www, for lamp var/www/html)

4.Open PHPMyAdmin (http://localhost/phpmyadmin)

5.Create a database with name ocasdb

6.Import ocasdb.sql file(given inside the zip package in SQL file folder)

7.Run the script http://localhost/ocas

Admin Credential Username: admin Password: Test@123

Teacher Credential Username: EMP12345 Password: Test@123 or Register a new Teacher through admin panel

User Credential Username: [email protected] Password: Test@123 or Register a new user

View Demo———————————

Project Download Link

Tags: College Assignment System Online College Assignment System Download Online College Assignment System Online College Assignment Project in Php Online College Assignment System Download Online College Assignment System in php Online College Assignment System Project Online College Assignment SystemProject for student

' src=

Hi! I am Anuj Kumar, a professional web developer with 5+ years of experience in this sector. I found PHPGurukul in September 2015. My keen interest in technology and sharing knowledge with others became the main reason for starting PHPGurukul. My basic aim is to offer all web development tutorials like PHP, PDO, jQuery, PHP oops, MySQL, etc. Apart from the tutorials, we also offer you PHP Projects, and we have around 100+ PHP Projects for you.

  • Next story  CRUD operation using PHP and MySQLi
  • Previous story  PHPGURUKUL TURN’S 5 YEAR’S OLD

Recommended Tutorials for you

You may also like....

Online Catering Management System Using PHP and MySQL project

Online Catering Management System Using PHP and MySQL

college-fee-system-php

College Fee System using PHP and MySQL

Yoga Classes Registration System using PHP and MySQL-project

Yoga Classes Registration System using PHP and MySQL

mcgs-php-project

Medical Card Generation System using PHP and MySQL

obdcms-project-php-mysql

Online Birth and Death Certificate System using PHP and MySQL

ocrs-project-php

Online Cloth Rental System using PHP and MySQL

Eahp Project php

Emergency Ambulance Hiring Portal using PHP and MySQL

support-ts-php-mysql

Support Ticket System using PHP and MySQL

ewaste-system-php

Electronic Waste Management system using PHP and MySQL

employee-attendance-system-php-mysql

Employees Attendance System using PHP and MySQL

mcbs-project-php-mysql

Meeting and Conference Booking System using PHP and MySQL

onss-project-php

Online Notes Sharing System using PHP and MySQL

college-alumni-php-project

College Alumni System using PHP and MySQL

emp-transport-system-php

Employee Transport System using PHP and MySQL

oms-php-mysqlproject

Orphanage Management System using PHP and MySQL

niv-tms-php

Nipah virus (NiV) – Testing Management System Using PHP and MySQL

toy-sho-php-project

Toy Shop Management System using PHP and MySQL

online-book-store-php-mysql

Online Book Store using PHP and MySQL

food-recipe-system-php-project

Food Recipe System Using PHP and MySQL

ocfrms-project-php-mysql

Online College Faculty Record Management System using PHP and MySQL

scholarship-management-system-php

Scholarship Management System using PHP and MySQL

rtbs-project-php

Restaurant Table Booking System using PHP and MySQL

tsas-project

Teacher Subject Allocation Management System using PHP and MySQL

ORCMS-project-php

Online Railway Catering Management System using PHP and MySQL

mhms-php

Maid Hiring Management System using PHP and MySQL

rpms--project-php

Rail Pass Management System using PHP and MySQL

Pre-School Enrollment System using PHP and MySQL

Pre-School Enrollment System using PHP and MySQL

bp-monitoring-system-php

BP Monitoring Management System using PHP and MySQL

art-gallery-php

Art Gallery Management System using PHP and MySQL

nms-php-project

Nursery Management System using PHP and MySQL

SSCMS-project

Student Study Center Management System using PHP and MySQL

rto-ms-project-php-mysql

RTO Management System Using PHP and MySQL

blms-php-project

Bank Locker Management System using PHP and MySQL

employee-ms

Employee Management System using PHP and MySQL

dams-project

Doctor Appointment Management System Using PHP and MySQL

ccams-project-php-mysql

CREDIT CARD Application Management System Using PHP and MySQL

covid-vaccination-ms-php-project

Covid Vaccination Management System using PHP and MySQL

osghs-php

Online Security Guards Hiring System using PHP and MySQL

crciket-academy-ms-project

Cricket Academy Management System Using PHP and MySQL

atsms-project-php

Auto/Taxi Stand Management System using PHP and MySQL

gms-project

Garbage Management System using PHP and MySQL

ldrms-project

Laptop and Desktop Rental Management System using PHP and MySQL

tsms-php-project

Traffic Squad Management System Using PHP and MySQL

fuel delivery project

Fuel Delivery Management System Using PHP and MySQL

ocmms-project-main

Online Course Material Management System using PHP and MySQL

oahms

Old Age Home Management System using PHP and MySQL

gym-ms-phpgurukul

GYM Management System using PHP and MySQL

ofrs

Online Fire Reporting System Using PHP and MySQL

otms-usingphp

Online Temple Management System using PHP and MySQL

edms-project

e-Diary Management System using PHP and MySQL

bms-php

Blog Management System using PHP and MySQL

etms-project-php

Employee Task Management System using PHP and MySQL

shoppingportal-proversion-project

Online Shopping Portal Pro Version using PHP and MySQL

obbs-project

Online Banquet Booking System using PHP and MySQL

jsms-project-main

Jewelry Shop Management System Using PHP and MySQL

dhms-project-main

Driver Hiring Management System Using PHP and MySQL

studemt-ms-php

Student Management System using PHP and MySQL

sanitizationmsusingphp

Sanitization Management System Using PHP and MySQL

newsportal ci

News Portal Using CodeIgniter

fwms-php

Food Waste Management System Using PHP & MySQL

ispms

Internet Service Provider Management System Using PHP and MySQL

bdmsusingci

Blood Donor Management System Using CodeIgniter

Home loan

Home Loan Management System Using PHP and MySQL

Car Washing Management System using PHP and MySQL

Car Washing Management System using PHP and MySQL

Curfew e-Pass Management System Using PHP and MySQL Pro Version

Curfew e-Pass Management System Using PHP and MySQL Pro Version

trms-ci-project

Teachers Record Management System using CodeIgniter

CSMS Project

Cold Storage Management System using PHP and MySQL

Baby daycare project

Baby Daycare Management System using PHP

pocms-project

Pre-owned/Used Car Selling Management System using PHP

DLMS Project Using PHP

Directory Listing Management System using PHP

Daily Expense Tracker System Pro Version Using PHP and mysql

Daily Expense Tracker System Pro Version Using PHP

ifscode-finder-uisngphp

IFSC Code Finder Project Using PHP

Vehicle Breakdown Assistance Management System project Using PHP

Vehicle Breakdown Assistance Management System Using PHP

mobile store project in php

Mobile Store Management System using PHP and MySQL

Men Salon Management System Project Using PHP and MySQL

Men Salon Management System Using PHP and MySQL

cake-bakery-system-using-php-mysql-project

Cake Bakery Management System Using PHP & MySQL

Bus Pass Management System Using PHP and MySQL

Bus Pass Management System Using PHP and MySQL

Lawyers Record Management System Using PHP and MySQL

Lawyers Record Management System Using PHP and MySQL

COMSMS Project

Computer Service Management System Using PHP and MySQL

COVID19 Testing Management System Using PHP and MySQL

COVID19 Testing Management System Using PHP and MySQL

Apartment Visitors Management System Developed using CodeIgniter

Apartment Visitors Management System Developed using CodeIgniter

User Management System in PHP using Stored Procedure

User Management System in PHP using Stored Procedure

Online Magazine Management System using PHP and MySQL project

Online Magazine Management System using PHP and MySQL

PHP Projects Free Download – Benefits of PHP Web Application Development

PHP Projects Free Download – Benefits of PHP Web Application Development

How to Download PHP Projects With Source Code?

How to Download PHP Projects With Source Code?

inventory-management-system-project

Inventory Management System Using PHP and MySQL

Online College Assignment System Using PHP and MySQL project

Zoo Management System Using PHP and MySQL

Theme Park Management System project

Theme Park Management System Using PHP and MYSQL

Online Dance Classes Registration System Using PHP and MySQL project

Online Dance Classes Registration System Using PHP and MySQL

ac-repairing-system-using-php-and-mysql-project

AC Repairing System Using PHP and MySQL

Complaint Management System Pro version using PHP and MySQL

Complaint Management System Pro version using PHP and MySQL

Crime Record Management System Using PHP and MySQ projectL

Crime Record Management System Using PHP and MySQL

Health Monitoring Management System Using PHP and MySQL project

Health Monitoring Management System Using PHP and MySQL

assignment with php

Online Furniture Shop Management System using PHP and MySQL

Online Marriage Registration System using PHP and MySQL

Online Marriage Registration System using PHP and MySQL

Daily Expense Tracker using CodeIgniter

Daily Expense Tracker using CodeIgniter

Hotel Booking Management System Using PHP and MySQL

Hotel Booking Management System Using PHP and MySQL

Curfew e-Pass Management System using PHP and MySQL

Curfew e-Pass Management System using PHP and MySQL

online Gas Booking System using PHP and MySQL

Online Gas Booking System Using PHP and MySQL

Online Tiffin Service System using PHP and MySQL

Online Tiffin Service System Using PHP and MySQL

Online Birth Certificate System Using PHP and MySQL

Online Birth Certificate System Using PHP and MySQL

Online DJ Booking Management System Using PHP and MySQL

Online DJ Booking Management System Using PHP and MySQL

Online Diagnostic Lab Management System using PHP and MySQL project

Online Diagnostic Lab Management System using PHP and MySQL

Park Ticketing Management System Using PHP and MySQL

Society Management System using PHP and MySQL

Dairy Farm Shop Management System Using PHP and MySQL

Dairy Farm Shop Management System Using PHP and MySQL

Movers and Packers Management System using PHP and MySQL project

Movers and Packers Management System using PHP and MySQL

Vehicle Rental Management System using PHP and MySQL project

Vehicle Rental Management System using PHP and MySQL

Local Services Search Engine Management System Using PHP and MySQL

Local Services Search Engine Management System Using PHP and MySQL

Client Management System Using PHP

Client Management System using PHP & MySQL

teachersrecordmanagementsystemusingphp

Teachers Record Management System Using PHP and MySQL

campus-recruitment--system-usingphp

Campus Recruitment Management System using PHP and MySQL

real-estate-management-system-using-php-mysql

Real Estate Management System Using PHP and MySQL

assignment with php

Toll Tax Management System using PHP and MySQL

Beauty Parlour Management System using PHP and MySQL

Beauty Parlour Management System using PHP and MySQL

assignment with php

Water Supply Management System Using PHP and MySQL

Cyber Cafe Management System Using PHP & MySQL

Cyber Cafe Management System Using PHP & MySQL

Pharmacy Management System using PHP and MySQL

Pharmacy Management System using PHP and MySQL

Car Showroom Management System Using PHP and MySQL

Car Showroom Management System Using PHP and MySQL

Apartment Visitors Management System using PHP and MySQL

Apartment Visitors Management System using PHP and MySQL

Vehicle Parking Management System

Vehicle Parking Management System using PHP and MySQL

paying-guest-accomodation-system-using-php

Paying Guest Accommodation System using PHP & MySQL

Event Management System Using PHP and MySQL

Event Management System Using PHP and MySQL

Daily-expense-tracker using php

Daily Expense Tracker Using PHP and MySQL

Car Driving School Management System Using PHP and MySQL

Car Driving School Management System Using PHP and MySQL

Attendance Monitoring System admin dashboard

Attendance Monitoring System using PHP and MySQL

food-ordering-system-using-php-mysql

Food Ordering System Using PHP and MySQL

Company Visitors Management System using PHP and MySQL

Company Visitors Management System using PHP and MySQL

assignment with php

Courier Management System Using PHP and MySQL

vehicle service management system

Vehicle Service Management System Using PHP and MySQL

Laundry Management System Using PHP and MySQL

Laundry Management System Using PHP and MySQL

Directory Management System (DMS)

Directory Management System Using PHP and MySQL

college-admission-management-system

College Admission Management System in PHP and MySQL

Insurance Management System in PHP and MySQL

Insurance Management System using PHP and MySQL

Employee Record Management System(ERMS

Employee Record Management System in PHP and MySQL

User Management System in CodeIgniter

User Management System in CodeIgniter

Contact form with mail function and Storing data in the database - Mini Project

Contact form with mail function and Storing data in the database – Mini Project

News Portal Project in PHP and MySql

News Portal Project in PHP and MySql

employee leave management system

Employee Leaves Management System (ELMS)

student result management system in php

Student Result Management system using PHP & MySQL

online library management system

Online Library Management System using PHP and MySQL

blood bank and donor management system

Blood Bank & Donor Management System using PHP and MySQL

Car Rental Project in PHP and Mysql

Car Rental Project in PHP and Mysql

tourism management system

Tourism Management System in PHP with Source code

complaint management System - PHPGurukul

Complaint Management System in PHP

Online Course Registration-Free Download

Online Course Registration Using PHP and MySQL

hospital management system

Hospital Management System In PHP

Smaal CRM in PHP

Small CRM in PHP

student record management system

Student Record System Using PHP and MySQL

assignment with php

Hostel Management System in PHP

shopping portal pro version

Online Shopping Portal Project

Job Portal Project in PHP

Job Portal Project using PHP and MySQL

user registration and login system in php

User Registration & Login and User Management System With admin panel

Welcome to PHPGurukul .

How can I help you?

🟢 Online | Privacy policy

Shintaro Fujinami

Shintaro Fujinami designated for assignment

by Jesse Garcia | Mets Correspondent | Fri, Jul 26th 1:34pm EDT

RHP Kodai Senga has been reinstated from the IL. RHP Adrian Houser has been designated for assignment. RHP Dedniel Núñez has been placed on the 15-day IL, retroactive to July 24, with a right pronator strain. — New York Mets (@Mets) July 26, 2024

Fantasy Impact:

Fujinami had been out of action with a shoulder strain and will not return to the Mets’ roster after being on a rehab assignment. He will hit the waiver wire.

Category: Transactions | More Shintaro Fujinami : News , Rankings , Projections , Stats

New York Mets News

  • DJ Stewart out of the lineup Friday By Jesse Garcia
  • Brandon Nimmo returns to the lineup Friday By Jesse Garcia
  • Eric Orze recalled from Triple-A By Jesse Garcia
  • Dedniel Nunez (forearm) placed on IL By Jesse Garcia
  • Adrian Houser designated for assignment By Jesse Garcia
  • Kodai Senga activated from IL By Jesse Garcia

Fantasy Baseball Articles

  • MLB DFS Picks, PrizePicks & Underdog Player Props: Friday (7/24) By Josh Shepardson
  • Fantasy Baseball Planner: Streamers, Two-Start Pitchers, Hitter Rankings (Week 18) By FantasyPros Staff
  • Fantasy Baseball Two-Start Pitchers: Rankings & Waiver Wire Pickups (Week 18) By FantasyPros Staff
  • Fantasy Baseball Streaming Pitchers: Rankings & Waiver Wire Pickups (Week 18) By FantasyPros Staff
  • Fantasy Baseball Pitcher Rankings: Week 18 (2024) By Ryan Pasti
  • Top 10 MLB PrizePicks Player Predictions: Friday (7/26) By FantasyPros Staff

What's your take? Leave a comment

Harvard Referencing Guide: Assignment example

  • List of general rules
  • Print Books
  • Journal articles
  • World wide web
  • Chapter from a book
  • Lecture Notes
  • Conference papers/Proceedings
  • Art works illustrated
  • Library quiz
  • Assignment example

`Assignment example

Assignment example with references and citations

Topic:   Cyberbullying and mental health among first-year students

First-year students are particularly susceptible to cyberbullying due to their heightened social anxieties. As they navigate a new social landscape, they are more likely to seek validation and acceptance, making them vulnerable to manipulation and harassment through online platforms.  The anonymity offered by the digital world emboldens bullies, who may feel less inhibited in their actions, leading to more aggressive and hurtful behaviour ( Hinduja & Patchin, 2010:25 ). 

According to Ybarra ( 2014:89), the constant accessibility of social media and instant messaging apps creates a constant stream of potential for bullying. Students may feel pressured to maintain a positive online presence, leading to anxiety and fear of negative online interactions.  This constant exposure to potential harassment can contribute to a heightened sense of vulnerability and insecurity, impacting their mental well-being

The consequences of cyberbullying on the mental health of first-year students can be profound. Research indicates a strong correlation between cyberbullying and increased symptoms of depression, anxiety, and suicidal ideation (Kowalski & Limber, 2013:56). Victims may experience feelings of isolation, shame, and loss of self-esteem, leading to difficulty forming healthy relationships and coping with academic pressures ( Smith et al., 2014:100) ( remember for the first time you write out all the authors).

Hinduja, S. & Patchin, J. W. (2010). Cyberbullying: An old problem in a new guise. Journal of Criminal Justice and Popular Culture , 17 (2):135-152.

Kowalski, R.M. & Limber, S. P. (2013). Cyberbullying: Bullying in the digital age. New York, NY: Routledge .

Smith, P. K., Mahdavi, J., Carvalho, C., & Fisher, B. (2014). Cyberbullying victimization: A systematic review of risk factors, interventions, and outcomes. Aggression and Violent Behavior , 19 (3): 164-176.

Ybarra, M. L. (2014). Cyberbullying: A review of the literature. Aggression and Violent Behavior , 19 (3): 137-14.

  • << Previous: Library quiz
  • Last Updated: Jul 23, 2024 11:59 AM
  • URL: https://spu-za.libguides.com/c.php?g=1256610

PHP Tutorial

Php advanced, mysql database, php examples, php reference, php oop - classes and objects.

A class is a template for objects, and an object is an instance of class.

Let's assume we have a class named Fruit. A Fruit can have properties like name, color, weight, etc. We can define variables like $name, $color, and $weight to hold the values of these properties.

When the individual objects (apple, banana, etc.) are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.

Define a Class

A class is defined by using the class keyword, followed by the name of the class and a pair of curly braces ({}). All its properties and methods go inside the braces:

Below we declare a class named Fruit consisting of two properties ($name and $color) and two methods set_name() and get_name() for setting and getting the $name property:

Note: In a class, variables are called properties and functions are called methods!

Define Objects

Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values.

Objects of a class are created using the new keyword.

In the example below, $apple and $banana are instances of the class Fruit:

In the example below, we add two more methods to class Fruit, for setting and getting the $color property:

Advertisement

PHP - The $this Keyword

The $this keyword refers to the current object, and is only available inside methods.

Look at the following example:

So, where can we change the value of the $name property? There are two ways:

1. Inside the class (by adding a set_name() method and use $this):

2. Outside the class (by directly changing the property value):

PHP - instanceof

You can use the instanceof keyword to check if an object belongs to a specific class:

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

assigning values to a variable in if condition in php

Can anybody explain how assigning values to variables work in php. I have the following code which does not work as expected (by me).

If I use this code account is 1, just ONE. How come??? getClientAccount returns string (username) or false if not user found. When user is found that 1 is returned. If I move the assignment above if statement, it works fine. I have similar problem when assining array returned by function to variable in if statement.

Alright, guys I think I discovered something, at least something for all of us here. Look at this code: http://codepad.org/QWjwl3vQ I think you will understand what is happening. Just try test1() and test2()

  • if-statement
  • variable-assignment

Jamol's user avatar

  • 1 Why semi colon in if statement condition ? –  Rikesh Commented Nov 21, 2013 at 6:31
  • edited. removed that semicolon. It was not in my code actually –  Jamol Commented Nov 21, 2013 at 6:43
  • If possible show your func. getClientAccount , so that one can have a better idea. –  Rikesh Commented Nov 21, 2013 at 6:50
  • Pay attention to my words: If I move the assignment above if statement, it works fine, as expected –  Jamol Commented Nov 21, 2013 at 7:34
  • Please have a look on edit. –  Jamol Commented Nov 21, 2013 at 7:43

6 Answers 6

After edit & checking your code it seems that boolean value is getting over write on the actual value. To get rid of this thing you need round braces on each condition for proper assignment called Operator Precedence .

Check your code that I have edited to make work as you expected.

Rikesh's user avatar

  • You made it. Thanks a lot. But I didn`t get why it was not working without extra braces –  Jamol Commented Nov 21, 2013 at 7:59
  • Your welcome !! Check the operator precedence reference I added in my answer for details. –  Rikesh Commented Nov 21, 2013 at 8:00

The first block of code is syntactically wrong.

Shankar Narayana Damodaran's user avatar

That's simply not a real question and there is no point in trying to answer it directly, especially if you aren't familiar with PHP syntax.

It's the OP's premises have to be questioned, not the code he's posted.

This code will plainly output the result of getClientAccount method (unless it's 0 or empty array).

So, the OP have to check what "was in the code actually" once more or verify the actual result of getClientAccount function.

Your Common Sense's user avatar

  • This your new question is totally different from one you asked. You have to make your mind before asking a question. –  Your Common Sense Commented Nov 21, 2013 at 8:22
  • It is exactly same thing. Read it carefully! –  Jamol Commented Nov 21, 2013 at 9:52
  • if you still think there is no difference, then you didn't get the answer you accepted –  Your Common Sense Commented Nov 21, 2013 at 10:03

Arpit Agrawal's user avatar

remove semicolon from if condition like following

and in your case php will check the value of $account variable after getting the returned value from the getClientAccount() function. if $account value ultimately mean true then it will execute your echo statement.

if you have any confusion about php boolean values then you can try it another way:

user3011768's user avatar

There are few syntax error. You need to remove the semi colon as mentioned already and you need to change to:

To check for a condition, at the moment you are trying to assign $account to $this->getClientAccount($request) result in a if statement. If statements are used to check conditions not to assign values.

Also $account already has to have a value otherwise your condition will always remain false, if the function returns a value.

J2D8T's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged php if-statement variable-assignment or ask your own question .

  • Featured on Meta
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Announcing a change to the data-dump process

Hot Network Questions

  • Photographing human iris without reflections
  • Can one be restricted from carrying a gun on the metro in New York city?
  • What do I do if my professor doesn't give me an extra credit assignment that he promised?
  • Extending Implicit Function Theorem to Show Global Existence
  • Is this an umlaut above a y in this 1922 Patronatsschein?
  • Why would these two populations be genetically compatible?
  • Why do some license agreements ask for the signee's date of birth?
  • Can I abort some of the attacks in a full attack action?
  • Undesired pagebreak in a list of tabularX
  • Why can generalized forces be derived from generalized potentials? Doesn't this confuse their relation to kinetic energy?
  • Submitting paper to lower tier journal instead of doing major revision at higher tier journal
  • Is any multi-qubit unitary operation a rotation about a specific unit vector?
  • Sci-fi show about a young girl that goes into a cyber world
  • Why doesn't "I never found the right one" use the present perfect?
  • Uniqueness results that follow from CH
  • Why did Kamala Harris once describe her own appearance at the start of an important meeting?
  • The vertiginous question: Why am I me and not someone else?
  • With SHA-1 broken, can the old Linux /dev/(u)random algorithm be trusted?
  • How can dragons breathe in space?
  • checkpointData in 2024
  • What are applicable skills and abilities for dealing with paperwork, administration and law in 5e?
  • How to calculate baker's percentages for indirect doughs?
  • Short story where a scientist develops a virus that renders everyone on Earth sterile
  • A hat puzzle question—how to prove the standard solution is optimal?

assignment with php

IMAGES

  1. Online College Assignment System Using PHP and MySQL| College

    assignment with php

  2. PHP Assignments for Students and Beginners

    assignment with php

  3. PHP Assignment For Students

    assignment with php

  4. Assignment Operators in PHP

    assignment with php

  5. Introduction to PHP Assignment Operators

    assignment with php

  6. PHP Assignment Operators with example

    assignment with php

VIDEO

  1. ASSIGNMENT

  2. PHP Variables , shorts

  3. Assignment php2

  4. PHP Assignment/Project 4

  5. PHP Assignment Operators

  6. Annamalai University CDOE Today Updates 👍

COMMENTS

  1. PHP: Assignment

    PHP is a popular general-purpose scripting language that powers everything from your blog to the most popular websites in the world. ... An exception to the usual assignment by value behaviour within PHP occurs with object s, which are assigned by reference. Objects may be explicitly copied via the clone keyword.

  2. PHP All Exercises & Assignments

    PHP All Exercises & Assignments. Practice your PHP skills using PHP Exercises & Assignments. Tutorials Class provides you exercises on PHP basics, variables, operators, loops, forms, and database. Once you learn PHP, it is important to practice to understand PHP concepts. This will also help you with preparing for PHP Interview Questions.

  3. PHP Assignment Operators

    Use PHP assignment operator ( =) to assign a value to a variable. The assignment expression returns the value assigned. Use arithmetic assignment operators to carry arithmetic operations and assign at the same time. Use concatenation assignment operator ( .= )to concatenate strings and assign the result to a variable in a single statement.

  4. PHP Operators

    PHP Assignment Operators. The PHP assignment operators are used with numeric values to write a value to a variable. The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right.

  5. PHP Assignment Operators

    In this tutorial, you shall learn about Assignment Operators in PHP, different Assignment Operators available in PHP, their symbols, and how to use them in PHP programs, with examples. Assignment Operators. Assignment Operators are used to perform to assign a value or modified value to a variable. Assignment Operators Table

  6. PHP

    PHP - Assignment Operators Examples - You can use assignment operators in PHP to assign values to variables. Assignment operators are shorthand notations to perform arithmetic or other operations while assigning a value to a variable. For instance, the = operator assigns the value on the right-hand side to the variable on the left-han

  7. PHP Assignment Operators

    PHP Assignment Operators. PHP assignment operators applied to assign the result of an expression to a variable. = is a fundamental assignment operator in PHP. It means that the left operand gets set to the value of the assignment expression on the right. Operator.

  8. php

    Before php 7 this would have given an Undefined index: foo notice. But with the null coalescing operator, that notice won't come up. But with the null coalescing operator, that notice won't come up. Share

  9. The PHP Handbook

    July 7, 2022 / #PHP. The PHP Handbook - Learn PHP for Beginners. Flavio Copes. PHP is an incredibly popular programming language. Statistics say it's used by 80% of all websites. It's the language that powers WordPress, the widely used content management system for websites. And it also powers a lot of different frameworks that make Web ...

  10. PHP assignment operators

    PHP Assignment Operators Last update on August 19 2022 21:51:14 (UTC/GMT +8 hours) Description. Assignment operators allow writing a value to a variable. The first operand must be a variable and the basic assignment operator is "=". The value of an assignment expression is the final value assigned to the variable.

  11. PHP Exercises, Practice, Solution

    Weekly Trends and Language Statistics. PHP Exercises, Practice, Solution: PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

  12. Learn PHP: Learn PHP Variables Cheatsheet

    In PHP, the reference assignment operator (=&) is used to create a new variable as an alias to an existing spot in memory. In other words, the reference assignment operator (=&) creates two variable names which point to the same value. So, changes to one variable will affect the other, without having to copy the existing data.

  13. PHP Examples

    Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.

  14. PHP Conditional Operator: Examples and Tips

    Conditional Assignment Operator in PHP is a shorthand operator that allow developers to assign values to variables based on certain conditions. In this article, we will explore how the various Conditional Assignment Operators in PHP simplify code and make it more readable. Let's begin with the ternary operator. Ternary Operator Syntax

  15. Online College Assignment System Using PHP and MySQL

    How to run the Online College Assignment System Project Using PHP and MySQL. 1.Download the zip file. 2.Extract the file and copy ocas folder. 3.Paste inside root directory(for xampp xampp/htdocs, for wamp wamp/www, for lamp var/www/html)

  16. Object Assignment in PHP

    An exception to the usual assignment by value behaviour within PHP occurs with objects, which are assigned by reference in PHP 5. Objects may be explicitly copied via the clone keyword. Share. Improve this answer. Follow edited Oct 19, 2012 at 12:53. answered Oct 19, 2012 ...

  17. Mike Trout feeling a bit better a day after leaving rehab assignment

    Trout, who went on the Injured List April 30 with a torn meniscus, lasted just two innings in his rehab assignment debut Tuesday with Salt Lake. Originally, the plan was for Trout to play five ...

  18. PHP Variables

    Rules for PHP variables: A variable starts with the $ 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 can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

  19. Shintaro Fujinami designated for assignment

    RHP Adrian Houser has been designated for assignment. RHP Dedniel Núñez has been placed on the 15-day IL, retroactive to July 24, with a right pronator strain. — New York Mets ...

  20. while loop in php with assignment operator

    Quite, yes. Even there is an assignment operator within that expression, the expression itself still stands for a value. ... PHP Collective Join the discussion. This question is in a collective: a subcommunity defined by tags with relevant content and experts.

  21. Mike Trout leaving rehab assignment, returning to Southern ...

    Mike Trout leaving rehab assignment, returning to Southern California to be re-evaluated. By SHANE LANTZ, Associated Press Updated July 24, 2024 5:18 p.m.

  22. LibGuides: Harvard Referencing Guide: Assignment example

    Assignment example with references and citations. Topic: Cyberbullying and mental health among first-year students. First-year students are particularly susceptible to cyberbullying due to their heightened social anxieties. As they navigate a new social landscape, they are more likely to seek validation and acceptance, making them vulnerable to ...

  23. php

    It should be noted that if you use multiple assignment on one line to assign an object, the object is assigned by reference. Therefore, if you change the value of the object's property using either variable, the value essentially changes in both. So I'll personally recommend that you assign the variables separately. For the record:

  24. PHP OOP

    Create your own server using Python, PHP, React.js, Node.js, Java, C#, etc. How To's. Large collection of code snippets for HTML, CSS and JavaScript. CSS Framework. Build fast and responsive sites using our free W3.CSS framework Browser Statistics. Read long term trends of browser usage ...

  25. assigning values to a variable in if condition in php

    That's simply not a real question and there is no point in trying to answer it directly, especially if you aren't familiar with PHP syntax.. It's the OP's premises have to be questioned, not the code he's posted.. This code will plainly output the result of getClientAccount method (unless it's 0 or empty array).. So, the OP have to check what "was in the code actually" once more or verify the ...