PHP Variables, Functions, Arrays, and Loops
by Alex Coleman | Build a Simple CodeIgniter App , CodeIgniter , Web App , Web Development
This is lesson four of a 10 ten-lesson course, Simple CodeIgniter App , which walks you through the creation of your first PHP web application using the CodeIgniter framework.
Before we jump into any writing code for our web app, it’s important discuss some of the basic concepts of programming in general.
And since we’ll be using it to write most of our app’s code, we’re going to use PHP to help demonstrate all of these concepts.
PHP is great to use as an example as it contains almost all of the common abilities shared nearly universally between the great majority of programming languages in existence.
A simple example
PHP lets you easily perform common tasks, such as mathematical operations, date and time calculations, and much more.
At its simplest, a snippet—or small piece of code—of PHP to calculate the result of 8 times 4 would look like this:
with the * representing the multiplication operator (which is the case in almost all programming languages, by the way).
Remember, as mentioned in a previous lesson, all blocks of PHP code must be surrounded by opening, <?php , and closing, ?> , PHP tags.
With that said, any number of lines of PHP code can exist within those opening and closing tags. So, for example, (as you’ll see later on) if we have an entire file filled with only PHP code, we only need one opening tag at the very beginning of the file and one ending tag at the very end.
Now back to our code. Just running an isolated calculation like 8 * 4 doesn’t do us a whole lot of good. Thankfully, PHP allows us to store pieces of information in variables .
Variables help us store information
Variables are named placeholders that allow us to reuse information throughout our code, simply by referring to them by name.
So, if we wanted to to store the result of our previous calculation (say, to use it again at a later point in time), we could do the following to store it in a variable named $result :
This effectively says to our code: “Compute the result of 8 times 4 (the right side of the equals sign) and store it (as designated by the equals sign, itself) in a variable named $result .”
Naming variables in PHP
Note that when defining a variable in PHP, its name must be preceded with the <em>$</em> symbol. Additionally, all variable names must be just one word, without spaces, containing only letters, numbers, and underscores, _ . Additionally, the name must start with a letter.
So, for example, <em>$result</em> , <em>$this_result_2</em> , and <em>$this_3rd_result</em> are all valid variable names in PHP.
The result of our calculation, 32 , is now stored in the variable $result . We can then, as mentioned, use it again within another piece of code, like so:
Using comments to explain your code
There are a few things to note in the code above. First, you can see the use of a comment in the first line:
Comments can be added as a way to describe a piece of code and are created by preceding a line with a double forward slash, // , as shown. Note that comments are not considered as actual lines of code , and they won’t ever have any effect on the code, itself. They’re simply there to make it clear— to someone else who may be reading your code (or to remind yourself)—as to what the code should be doing.
If we wanted that same comment to span multiple lines, we could begin it with /* and end it with */ , like so:
which is known as a block comment .
And finally, every operational line of code —every line directly responsible for some functionality, such as defining a variable or performing a calculation— must end with a semicolon , ; . The semicolon essentially says to the code, “Okay, this operation is now complete. Move on to the next, please!”
Printing things out
Very frequently when building our app, we’ll be using PHP to print out pieces of information in amongst HTML code.
To accomplish that, we’ll use PHP’s echo function.
For example, to print out a simple piece of text, we might write the following code:
which, when used within a webpage’s code, would simply display:
within a browser.
Note that you can also print out the values of variables:
which would display:
Packaging code functionality using functions
Frequently, when coding, you’ll write a group of code lines all designed to work together to perform a specific task.
In PHP (as well as in all other programming languages), we’re given a very convenient way to organize such pieces of code: by defining functions .
Let’s take the following (simple) example of a PHP function that can be used to print out someone’s name:
Notice that the above function accepts one parameter : $name . Parameters are used to allow us to pass required information into a function. In this case, our function does not work properly unless we pass it a name.
We can call our function (i.e. execute it) by using its name and passing in the necessary parameter value(s), like so:
The above code would print out:
by joining three strings: "My name is” ; the value of our $name variable that was passed in ( "Alex” in the example above); and the string containing just a period, ".” , to end the sentence.
You also just saw the first example usage of string concatenation —combining multiple strings into one. In PHP, this is done using the concatenation operator , . , which, as you can see, is just a dot/period.
Operators allow us to perform various operations, such as joining two strings with the dot, . , operator or comparing two numbers with greater than, > , or less than, < operators.
To return or not to return: two examples
Functions have the ability to send information back to the location in the code from which they were originally called. When they do this, it’s referred to as returning .
All functions can either: a) return some sort of information; or b) not return anything. Both are used quite frequently—whether or not a function returns any information is totally dependent on the situation it’s handling.
Let’s take two examples to describe when it may, and may not, be appropriate for a function to return information.
In our first example, we have a function that’s used to print out the brand, model, and color of a car.
The function, as well as a piece of code that executes it, may look something like this:
In this case, there’s no information that needs to be returned for further use; we’re simply printing out a string.
Now let’s take a second example where we do need our function to return some information.
Let’s say we have four numbers and we want to: multiply the first two together; multiply the last two together; and then get the sum of those two results.
The function and additional code to accomplish that may look like this:
In the example above, you can see that our function does something rather simple: multiplies two numbers together. What’s important is the fact that it returns that result so that it can be stored in a variable and used at a later time .
We begin with our four initial numbers. We then pass the first two numbers into our multiply_numbers function, returning that $result , and storing that value in our $first_times_second variable.
Without that last return statement in our function, we would never have access to the resulting value, as it would never be sent back to the place in our code where we originally called the function. But with the return statement, we get the resulting value.
We can then do the same thing for our third and fourth numbers, and finally, retrieve our $answer value by summing those two results.
Variable and function locations and scope
You may have noticed in the previous code example that our function was defined at the top and then called afterwards:
That’s generally good practice—defining functions before they’re called—but it’s not entirely necessary. When a PHP file is accessed, all of its functions are initialized before any of the other lines of code are executed. So as long as a function is defined in the same file, it can be called from anywhere within that file.
For example, we could have called our multiply_numbers function before it was defined, and we still would’ve gotten the desired results:
This is also a good time to address a concept known as scope . The scope of a variable refers to the domain within which it can be referenced.
In the case of functions, their code is entirely self-contained, so any variables initialized and contained within a function itself are only available within that function . Let’s look at an example:
In the code above, we have a function, example_function , and within that function, we’ve define a variable, $function_var . The function’s code is completely valid. We define a variable and then return it.
But below that, you see another statement, outside of the function , trying to echo the $function_var variable that was created inside of example_function . That line of code is invalid , as the $function_var does not exist outside of example_function .
And that’s a perfect demonstration of why we require the use of return statements— to make use of values contained within a function outside of it.
Using arrays to store multiple items at once
In programming, one of the most commonly used data structures (i.e. a particular way of storing or representing data) is the array .
An array is used to store a group of associated values, together. And as you’ll see as we progress through building our app, they’ll become extremely useful in all sorts of different situations.
Let’s look at an example to see how arrays function. In this example, we’ll be using an array to store a group of numbers.
Adding items to an array
Let’s start by creating an empty array:
Now, let’s add a few numbers to it:
Great! Now our array contains three numbers: 1, 2, and 3. In PHP, you’ll notice that the syntax for initializing a new, empty array is:
and the syntax for adding an item to an array is:
where $array_name is the name of the array variable, immediately followed by open- and closed-brackets,  , followed by the equals sign and the value you wish to add to the array.
Creating an array with items in it right off the bat
Above, we created our array first and then proceeded to add values to it after the fact. In PHP, you can also create an array initially that already includes values. To create our same numbers array in this manner, we could write:
The values you wish to include in the array are simply included within the array function’s parentheses, separated by commas, as seen above. And we’re not restricted to a certain number of values; we could create an array with 50 or even 500 initial values, if desired.
Arrays are like dictionaries
In PHP, arrays act, essentially, like dictionaries: you add an item to the array and assign it an associated key, so that you look the item up by that key later on. In an actual dictionary, you have words and their associated definitions; in arrays, you have keys and their associated items, or values.
So, for example, if you were to add a value to an array with the key 'dog’ , you would later be able to look up/retrieve that value using the 'dog’ key:
Note that this is very similar to a dictionary: you know a word (i.e. the key), say “computer”, and you can look up its definition (i.e. the value) by locating it in the dictionary, as depicted below.
Retrieving array values where keys weren’t specified
On the other hand, if you created an array without explicitly designating keys:
auto-incrementing integers, starting at 0, are automatically assigned as keys. So, for example, to retrieve to first value in the array, you would use:
And to retrieve the third value, you could use:
Programming indexes start at 0, not 1
In almost all areas of programming, when you’re talking about the index, or location within a larger group, of an item, the count starts at 0, not 1, as depicted:
Using loops to perform multiple operations
Frequently—in all kinds of programming, including web development—we need to either: 1) perform a very similar operation, many times in a row; or 2) iterate , or cycle, through a collection of items—such as an array—and perform a certain function on each item.
To accomplish that, we can use what’s known in programming as a loop .
foreach loop example
Let’s take a look at a quick example. Say we have an array of numbers—such as the $our_numbers array we created above—and we want to find the square root of each of them. In programming, we can very conveniently use a loop to help us do just that:
As you see above, we start off with our initial array of numbers, $our_numbers , as well as a new, empty array, $our_numbers_roots , which will store the square root values we’ll be computing.
We then utilize a foreach loop to cycle through all of our numbers.
foreach loops allow us to take an array of items and go through each one, starting with the first one and automatically ending with the last one.
As seen above, the syntax for a foreach loop is as follows:
The structure of a foreach loop
The parentheses immediately following the foreach contain the following three
- the name of the array that we wish to loop through;
- followed by the keyword as;
- and a variable that represents the current item, which can be named anything of our choosing (as you see in the example above, we used the variable named $num to represent each individual number as we looped through them).
The process of looping through an array’s items using a foreach loop is demonstrated in the figure below.
In PHP (and again, nearly all other programming languages) we also have what’s known as a for loop, which functions slightly differently than our foreach loop.
for loops take on the format:
So, for example, if we wanted to generate an array of numbers to represent the different months in the year, we could do the following:
That translates to the following:
- “Start with a variable, $i , equal to 1 ;
- as long as $i is less than or equal to 12 , continue looping;
- after each loop, increment $i by one ( $i++ , which is the same exact thing as $i = $i + 1 )”.
That means that our loop will run the first time with $i equal to 1. After that, $i will be incremented by 1 —updating its value to 2 —which is still less than 12 , so the loop will run again.
And so on, all the way through $i being equal to 12 .
After that, $i will be incremented and set to 13 , and our condition, $i <= 12 will return false , thus exiting the loop.
You can see how this loop works perfectly for generating a list of numbers in order.
You now have a solid background of some of the most important, fundamental concepts in all of programming: variables , functions , arrays , and loops .
And we’ll continue to use all of these concepts throughout the remainder of the course as we build our web app, so feel free to refer back to this lesson as often as you’d like.
Now it’s time to put your new knowledge into action.
Week 4 Task
Write some php code of your own that utilizes variables, functions, arrays, and loops..
Now that you have an understanding of these four coding concepts and have seen multiple examples of each, it’s time to write some code of your own that puts them to work. After working through the previous lessons, you should already have your computer set up for writing PHP code.
1. Create a new file
Start by creating a new test.php file directly within your web root directory ( C:wampwww for Windows; /Application/MAMP/htdocs for Mac), and open it up within Sublime Text.
2. Complete the following exercise (or feel free to come up with one on your own!)
- Create an array that contains a few names—maybe one that contains your name as well as a few of your friends’ names.
- Write a function that accepts two parameters—a person’s name and the number they are within the array (i.e. the second person’s number would be 2)—and returns a message in the format: “[name] is person #[number].” (So an example message may be “Alex is person #1.”)
- Use a loop to iterate through your array, calling your function to print out all of these messages. Remember that you’ll have to somehow keep track of what number person you’re on. ( Hint : you can use a counter to do this.)
When you’re finished, leave a comment below with your working code. (Make sure to test it by accessing your new file it within your browser!)
- Have your array store both names and the person’s relationship to you. So, if you’re adding your sister Jane, her “name” would be “Jane” and her relationship (to you) would be “sister”. ( Hint : You’ll need to use a multidimensional array in order to accomplish this.)
- Then alter your function to accept three parameters—name, number, and relationship— and return a message in the format: “[name] is person #[number] and is my [relationship].” (e.g. “Jane is person #1 and is my sister.”)
And as always, feel free to send me an email or leave a comment with any questions you have or reach out if you get stuck. I’m always here to help!
Home » PHP Tutorial » PHP Variables
Summary : in this tutorial, you will learn how to use PHP variables to store data in programs.
Define a variable
A variable stores a value of any type, e.g., a string , a number , an array , or an object .
A variable has a name and is associated with a value. To define a variable, you use the following syntax:
When defining a variable, you need to follow these rules:
- The variable name must start with the dollar sign ( $ ).
- The first character after the dollar sign ( $ ) must be a letter ( a-z ) or the underscore ( _ ).
- The remaining characters can be underscores, letters, or numbers.
PHP variables are case-sensitive. It means that $message and $Message variables are entirely different.
The following example defines a variable called $title :
To display the values of variables on a webpage, you’ll use the echo construct. For example:
If you open the page, you’ll see the following message:
Another shorter way to show the value of a variable on a page is to use the following syntax:
For example, the following shows the value of the $title variable in the heading:
Mixing PHP code with HTML will make the code unmaintainable, especially when the application grows. To avoid this, you can separate the code into separate files. For example:
- index.php – store the logic for defining and assigning value to variables.
- index.view.php – store the code that displays the variables.
- Use the require construct to include the code from the index.view.php in the index.php file.
The following shows the contents of the index.view.php file:
And the following shows the contents of the index.php file:
If you open the index.php file on the web browser, you’ll see the same output.
By doing this, you separate the code responsible for logic and the code responsible for displaying the file. This is called the separation of concerns (SoC) in programming.
- A variable stores a value, and its name always starts with $ sign.
- Use the separation of concerns principle to separate the PHP logic from HTML.
- How to assign multiple variables at once in PHP
I n this tutorial, we’re going to see different possibilities to define several variables at once in PHP.
If you want to define several variables at once, a notation that is often expected would be to separate them with commas. In PHP this leads to a parse error.
Use the following notation to assign multiple values to a single variable:
Example : Assign multiple variables at once
With the combination of list() and an array , several variables can be assigned different values. However, this notation is more difficult to read and in order to assign the same value to several variables, it must be entered in the array as often as necessary.
- Factorial Program in PHP Using Recursive Function
- Factorial in PHP Using For Loop
- How to Generate Random String in PHP
- Warning: Cannot modify header information – headers already sent
- How to send mail from localhost in PHP using WAMP server
- How to send mail from localhost in PHP using XAMPP
- How to Send an Email in PHP
- How to Validate an Email Address in PHP
- How to Check Format of Date in PHP
- How to check if a URL is valid in PHP
- How to Check Website Availability with PHP
- How to Generate Random Numbers in PHP
- How to Calculate Age from Date of Birth in PHP
- How to Extract Content Between HTML Tags in PHP
- How to check if file exists on remote server PHP
- How to get the client IP address in PHP
- How to Get IP Address of Server in PHP
- How to declare a global variable in PHP
- How to refresh a page with PHP
- How to get first day of week in PHP
- How to Change Max Size of File Upload in PHP
- How to compare two dates in PHP
- How to open a PDF file in browser with PHP
- How to Download file from URL using PHP
- How to remove an array element based on key in PHP
- How to get random value from an array in PHP
- How to calculate sum of an array in PHP
- How to remove null or empty values from an array in PHP
- How to Populate Dropdown List using Array in PHP
- How to get all the keys of an associative array in PHP
- How to get a value from an array in PHP
- How to remove a specific element from an array in PHP
- How to sort an associative array by value in PHP
- How to sort an associative array by key in PHP
- How to Check If a String Contains a Specific Word in PHP
- How to get the current date and time in PHP
- How to redirect to another page in PHP
- How to remove all spaces from a string in PHP
- Convert a date DD-MM-YYYY to YYYY-MM-DD in PHP
- Convert a date YYYY-MM-DD to DD-MM-YYYY in PHP
- How to get the current year in PHP
- How to convert a string to an integer in PHP
- How to get the first element of an array in PHP
- How to convert date to timestamp in PHP
- PHP: Compare two arrays and get the difference
- How to remove duplicates from an array in PHP
- How to sort an array in alphabetical order in PHP
- How to merge multiple arrays into one array in PHP
- How to add an element to the end of an array in PHP
- How to add an element to the beginning of an array in PHP
- How to remove the last element from an array in PHP
- How to remove the first element from an array in PHP
- How to replace part of a string in PHP
- How to count repeated words in a string in PHP
- PHP – Count Array Elements
- How to Reverse an Array in PHP
- How to check if a value exists in an array in PHP
- How to check if a key exists in an array in PHP
How to reverse a string in PHP
- How to check if a variable is null in PHP
- How to check if a variable is empty in PHP
- How to check if a variable is undefined in PHP
- Convert HTML entities back to characters – PHP
- How to find the length of a string in PHP
- How to capitalize the first letter of a string in PHP
- PHP – Uppercase the first letter of each word in a string
- How to convert a string to lowercase in PHP
- How to compare two strings in PHP
- How to get the URL of the current page in PHP
- How to convert a string into an array in PHP
- How to extract a substring from a string in PHP
- How to count number of words in a string in PHP
- How to remove special characters from a string in PHP
- How to replace a word in a string in PHP
- How to Concatenate Two Strings in PHP
- How to count the number of characters in a string in PHP
- PHP – Remove spaces at the beginning and end of a string
- How to filter an array by value in PHP
- PHP – Get Domain Name from URL
- How to create a log file in PHP
- How to add days to a date in PHP
- PHP – Get file extension
- How to save an image from a URL in PHP
- How to Edit PHP ini File in Ubuntu Terminal
- How to increase the execution time of a PHP script
- How to enable cURL in PHP WAMP, XAMPP, and Ubuntu
- Convert Array to JSON in PHP
- PHP – Read JSON file
- How to display HTML tags as plain text using PHP
- PHP – Create JSON file
- How to convert result of MySQL query in JSON format
- PHP – Read CSV File into an Array
- How to convert an object to associative array in PHP
- How to extract or unzip a folder on FTP server in PHP
- How to Import CSV File in MySQL PHP
- Get Data From a Database Without Refreshing the Browser Using Ajax
- How to connect to Oracle database with PHP
- Connect to a PostgreSQL database with PHP PDO
- PHP – Convert Multidimensional Array to XML file
- What is PHP and how can I learn it?
- Hello World in PHP
- Comments in PHP
- How to Define a Variable in PHP
- PHP global variable with Example
- PHP Variable Scope
- PHP – Static Variables
- Type casting in PHP
- PHP Type Juggling
- Variable variables in PHP
- How to echo an array in PHP?
- How to Convert Decimal to Binary in PHP?
- How to Convert Binary to Decimal in PHP?
- How to extract $_GET / $_POST parameters in PHP
- How to use $_GET in PHP?
How to get a variable name as a string in PHP?
- How to print all defined variables and values in PHP
- PHP References: When to Use Them, and How They Work
- List of Superglobal Variables in PHP
- How to return a variable by name from a function in PHP
- How to delete a variable in PHP
- What is the difference between == and === in PHP
- How to check if a variable is NULL in PHP?
- How to check if an object is an instance of a specific class in PHP?
How to check if a variable is a Boolean in PHP?
- How to check if a variable is a String in PHP?
- How to check if a variable is an Integer in PHP?
- How to check if a variable is a float in PHP?
- How to check if a variable is an array in PHP?
- How to check if a variable is undefined in PHP?
- How do you determine the data type of a variable in PHP?
- Difference between Include and Require in PHP
- How to combine HTML and PHP?
- How to add a new line within echo in PHP?
- How to display PHP variable values with echo, print_r, and var_dump
- The 6 best PHP frameworks in 2021
- PHP MCQ – Multiple Choice Questions and Answers – Basics – Part 1
- PHP MCQ – Multiple Choice Questions and Answers – Basics – Part 2
- PHP MCQ – Multiple Choice Questions and Answers – Basics – Part 3
- PHP Questions and Answers – Functions – Part 1
- PHP Questions and Answers – Functions – Part 2
- PHP Questions and Answers – Arrays – Part 1
- PHP Questions and Answers – Arrays – Part 2
- PHP Questions and Answers – Arrays – Part 3
- PHP Questions and Answers – Arrays – Part 4
- PHP Questions and Answers – Object-Oriented OOP – Part 1
- PHP Questions and Answers – Object-Oriented OOP – Part 2
- PHP Questions and Answers – Object-Oriented OOP – Part 3
- PHP Questions and Answers – String – Part 1
- PHP Questions and Answers – String – Part 2
- PHP Questions and Answers – Regular Expressions
- PHP Questions and Answers – Exception Handling
You May Also Like
Leave a Reply Cancel reply
Your email address will not be published. Required fields are marked *
Save my name, email, and website in this browser for the next time I comment.
Buckle up, fellow PHP enthusiast! We're loading up the rocket fuel for your coding adventures...
- Best Practices ,
How do I assign values to variables using assignment operators in PHP?
Hey everyone, I'm relatively new to PHP and I'm struggling with assigning values to variables using assignment operators. I understand that assignment operators are used to assign values to variables, but I'm not sure how to properly implement them in my code. Could someone please help me out and explain the process? I've been trying to assign values to variables using the assignment operator (=), but I'm not sure if there are any other operators that I should be using. Are there different assignment operators in PHP, and if so, how do they differ from each other? It would be really helpful if someone could provide me with some examples or code snippets to demonstrate how assignment operators are used in PHP. Additionally, if there are any best practices or common pitfalls to avoid when using assignment operators, please do share them. Thank you in advance for your assistance! - PHP novice
Hey there, I totally understand where you're coming from! When I first started learning PHP, I had trouble grasping how to assign values to variables using assignment operators. It can be a little tricky at the beginning, but with some practice, it becomes much easier. In PHP, the most commonly used assignment operator is the equals sign (=). It allows you to assign a value to a variable. For example, if you have a variable called $age and you want to assign the value 25 to it, you would use the assignment operator like this: $age = 25; However, PHP offers a variety of other assignment operators to make your coding life even easier. Let me give you a quick overview of a few of them: 1. Addition assignment (+=): This operator allows you to add a value to an existing variable and update the variable with the result. Let's say you have a variable called $total set to 100, and you want to add 10 to it. You can use the addition assignment operator like this: $total += 10; 2. Subtraction assignment (-=): This operator is used to subtract a value from an existing variable and store the updated value back into the variable. For example, if you have a variable called $balance set to 500 and you want to subtract 50 from it, you can use the subtraction assignment operator like this: $balance -= 50; 3. Multiplication assignment (*=): This operator allows you to multiply the value of a variable by a specific number and update the variable accordingly. Suppose you have a variable called $quantity with a value of 5, and you want to multiply it by 2. You can use the multiplication assignment operator like this: $quantity *= 2; 4. Division assignment (/=): This operator divides the value of a variable by a given number and stores the result back into the variable. For instance, if you have a variable called $total with a value of 1000, and you want to divide it by 5, you can use the division assignment operator like this: $total /= 5; These assignment operators come in handy when you need to perform mathematical operations on variables and update their values accordingly. Remember, the key thing to keep in mind is that the variable you want to modify should be on the left-hand side of the assignment operator. I hope this explanation helps! If you have any more questions, feel free to ask. All the best, [Your Name]
Hey there, I completely understand your struggle with assigning values to variables using assignment operators in PHP. When I started learning PHP, I faced similar challenges, but with some practice and exploration, it became much clearer. In PHP, the assignment operator is denoted by the equals sign (=), and it allows you to assign a value to a variable. For example, let's say we have a variable called $username, and we want to assign the value "john123" to it. We can simply use the assignment operator like this: $username = "john123"; Now, besides the basic assignment operator, PHP also offers a variety of compound assignment operators that can come in handy. One such operator is the addition assignment operator (+=). This operator allows you to add a value to an existing variable and update its value in a concise way. For instance, if you have a variable $count with a value of 5, and you want to add 3 to it, you can use the addition assignment operator like this: $count += 3; Similarly, there are other compound assignment operators like subtraction assignment (-=), multiplication assignment (*=), and division assignment (/=). These operators perform the corresponding operation on the variable and update its value in a single step. It's important to note that these compound assignment operators not only make your code shorter but also improve its readability. They can be especially useful when performing calculations or updating variables based on certain conditions. Remember, the variable you want to modify should be on the left-hand side of the assignment operator. I hope this helps clarify the concept of assigning values to variables using assignment operators in PHP. If you have any more questions or need further assistance, feel free to ask! Best regards, [Your Name]
Hey there, I understand your struggle, as I went through a similar learning phase when I started with PHP. Assigning values to variables using assignment operators is quite straightforward, but it can be a bit confusing at first. In PHP, the most commonly used assignment operator is the equals sign (=). It allows you to assign a value to a variable. For example, let's say we have a variable called $name and we want to assign the value "John" to it. We can do so by using the assignment operator like this: $name = "John"; Additionally, there are some other assignment operators you can use to make your code more concise. The most common ones include: - Addition assignment (+=): This operator allows you to add a value to an existing variable and assign the result back to the same variable. For example, if you have a variable $count with a value of 5, you can increase its value by 2 using the statement: $count += 2; - Subtraction assignment (-=): Similarly, you can subtract a value from an existing variable using this operator. For example, if you have a variable $total with a value of 10, you can decrease it by 3 with: $total -= 3; - Multiplication assignment (*=): This operator allows you to multiply a variable by a value and assign the result back to the same variable. For instance, if you have a variable $price with a value of 20, you can multiply it by 1.1 (to add 10% tax) using: $price *= 1.1; - Division assignment (/=): Likewise, you can divide a variable by a value and assign the result back to the same variable. For example, if you have a variable $quantity with a value of 100, you can divide it by 5 using: $quantity /= 5; These assignment operators can save you some typing and make your code more concise. It's important to note that assignment operators modify the value of the variable on the left-hand side of the operator. So, if you want to assign a value to a specific variable, make sure it is on the left-hand side of the assignment operator. I hope that clears things up a bit for you. If you have any more questions, feel free to ask! Best regards, [Your Name]
More Topics Related to PHP
- What are the recommended PHP versions for different operating systems?
- Can I install PHP without root/administrator access?
- How can I verify the integrity of the PHP installation files?
- Are there any specific considerations when installing PHP on a shared hosting environment?
- Is it possible to install PHP alongside other programming languages like Python or Ruby?
More Topics Related to Assistance
- What additional software or libraries are required to install PHP on a Unix system?
- How can I install PHP on Windows Server Core, which does not have a graphical interface?
- How can I configure PHP to work with Microsoft IIS (Internet Information Services) on Windows?
- How can I compile or build PECL extensions from source code if pre-compiled packages are not available?
More Topics Related to Best Practices
- What is the recommended approach for installing PHP on a container orchestration platform like Kubernetes?
- Are there any specific considerations when installing PHP on a high-availability cluster or a distributed system?
- How can I ensure PHP installations remain up to date with the latest security patches and bug fixes?
- Are there any considerations for installing PHP on CentOS or Red Hat Enterprise Linux?
- Best Practices
- Web Development
New to LearnPHP.org Community?
- 90% Refund @Courses
- PHP Tutorial
- PHP Calendar
- PHP Filesystem
- PHP Programs
- PHP Interview Questions
- PHP IntlChar
- PHP Image Processing
- PHP Array Programs
- PHP String Programs
- PHP Formatter
- Web Technology
- Solve Coding Problems
- How to Pass an Array into a Function in PHP ?
- PHP Program to Print Diamond Shape Star Pattern
- How to Define an Empty Object in PHP ?
- What is the difference between implements and extends in PHP ?
- What are getters and setters methods in PHP ?
- How to Validate Password using Regular Expressions in PHP ?
- How to Create MD5 Hashes in PHP ?
- How to Convert Byte Array to JSON in PHP ?
- How hash Function works in PHP ?
- PHP Program to Sort Names in an Alphabetical Order
- How to Push Both Key and Value into PHP Array ?
- How to Get Current Time in Milliseconds in PHP ?
- How to Convert Seconds into Hours and Minutes in PHP ?
- Check if a Given Number is Fibonacci Number in PHP
- How to Flatten Multidimentional Array in PHP ?
- How to Get All Possible Pairs in Array using PHP ?
- How to Find Matching Pair from an Array in PHP ?
- How to Replace an Element Inside Array in PHP ?
- PHP Program to Find All Prime Numbers in a Given Interval
How to Assign Multiple Variables in One Line in PHP ?
In PHP , assigning multiple variables in one line can be a handy and efficient way to streamline your code. This technique not only makes your code more concise but also improves readability. There are several approaches to achieve this, each with its own syntax and use cases.
Table of Content
Using Multiple Assignment
Using list() function, using explode() function, using short array syntax.
PHP allows multiple variables to be assigned the same value in a single line.
The list() function is a versatile way to assign multiple variables at once. It allows you to assign values from an array to individual variables in a single line.
The explode() function is useful when dealing with delimited strings. It splits a string into an array based on a specified delimiter and assigns the values to variables.
PHP 5.4 introduced a short array syntax, making it more convenient to assign multiple variables in a single line.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now !
Please Login to comment...
- Geeks Premier League 2023
- Geeks Premier League
- Web Technologies
- 10 Best ChatGPT Prompts for Novel and Fiction Book Writing
- Top 10 AI-Powered Music Mixing Tools for Musicians and Producers
- 10 Best ChatGPT Prompts to Streamline Project Management
- How to Use ChatGPT in Telegram: Easy & Quick Methods
- 30 OOPs Interview Questions and Answers (2024)
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
- Sign In | Sign Up -->
- CONTACT | HELP
- ABOUT AIMTOCODE
- PHP INTRODUCTION
- PHP EVALUATION
- PHP VARIABLE
- PHP CONSTANT
- PHP FUNCTION
- BUILT-IN FUNCTION
- USER DEFINED FUNCTION
- ERROR HANDLING
- PHP DATA TYPES
- PHP INTEGER DATATYPE
- PHP DOUBLE DATATYPE
- PHP STRING DATATYPE
- PHP NULL DATATYPE
- PHP BOOLEAN DATATYPE
- PHP ARRAY DATATYPE
- PHP OBJECT DATATYPE
- PHP RESOURCE DATATYPE
- PHP CONTROL STATEMENT
- SIMPLE IF STATEMENT
- PHP IF-ELSE STATEMENT
- PHP ELSE-IF STATEMENT
- PHP SWITCH STATEMENT
- PHP LOOP STATEMENT
- PHP WHILE LOOP
- PHP DO-WHILE LOOP
- PHP FOR-LOOP
- PHP FOREACH LOOP
- PHP OPERATORS
- ARITHMETIC OPERATOR
- LOGICAL OPERATORS
- ASSIGNMENT OPERATOR
- INCREMENT OPERATOR
- DECREMENT OPERATOR
- STRING OPERATOR
- ARRAY OPERATOR
- PHP-FILE HANDLING
- FILE READ FUNCTION
- FILE WRITE FUNCTION
- FILE OPEN FUNCTION
- FILE CLOSE FUNCTION
- FILE COPY FUNCTION
- FILE DELETE FUNCTION
Assigning Variable in PHP with Example
Definition of php.
The PHP Stands for Hypertext Pre-processor. PHP is a programming language that allows web developers to create dynamic content that interacts with databases.
PHP Variable types
- The main way to store information is by using a variable.
- All variables in PHP are denoted with a leading dollar sign($).
- The value of a variable is the value of its most recent assignment.
- Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right.
- Variables used before they are assigned have default values.
A variable in PHP is a name of memory location that holds data. A variable is a temporary storage that is used to store data temporarily.
PHP has a total of eight data types: Integers, Doubles, Booleans, NULL, Strings, Arrays, Objects and Resources (it is a special variable).
PHP variable Rules
- PHP variables must start with letter or underscore only.
- PHP variable can't be start with numbers and special symbols.
Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types:
- Local variables
- Global variables
- Staticc variables
- A constant is a name or an identifier for a simple value.
- A constant value cannnot change during the execution of he script.
- By default a constant is case-sensitive.
- By convention, constant identifiers are always uppercase.
- A constant name statrs with a letter or underscore, followed by any number of letters, numbers, or underscores.
- To define a constant, use define() function and retrieve the value of a constant.
- The function constant() is used to read a constant's value.
PHP provides a large number of predefined constants to any script which it runs.
There are Basically five magical constants that change depending on where they are used.
The current line number of the file where it is used.
Example: php _LINE_
Example: php _file_.
Represents full path and file name of the file. If it is used inside an include, name of included file is returned.
Example: Php _FUNCTION_
_FUNCTION_ Represents the function name where it is used. If it is used outside of any function, then it will return blank. _METHOD_ Represents the class name where it is used. If it is used outside of any function, then it will return blank. _CLASS_ Represents the name of the class method where it is used. The method name is returned as it was declared.
- Language Reference
The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. For example:
Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:
This script will generate an undefined variable E_WARNING (or a E_NOTICE prior to PHP 8.0.0) diagnostic. However, if the display_errors INI setting is set to hide such diagnostics then nothing at all will be outputted. This is because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.
The global keyword
First, an example use of global :
Example #1 Using global
The above script will output 3 . By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.
A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as:
Example #2 Using $GLOBALS instead of global
The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal . Here's an example demonstrating the power of superglobals:
Example #3 Example demonstrating superglobals and scope
Note : Using global keyword outside a function is not an error. It can be used if the file is included from inside a function.
Using static variables
Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example:
Example #4 Example demonstrating need for static variables
This function is quite useless since every time it is called it sets $a to 0 and prints 0 . The $a ++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:
Example #5 Example use of static variables
Now, $a is initialized only in first call of function and every time the test() function is called it will print the value of $a and increment it.
Static variables also provide one way to deal with recursive functions. A recursive function is one which calls itself. Care must be taken when writing a recursive function because it is possible to make it recurse indefinitely. You must make sure you have an adequate way of terminating the recursion. The following simple function recursively counts to 10, using the static variable $count to know when to stop:
Example #6 Static variables with recursive functions
Static variables can be assigned values which are the result of constant expressions, but dynamic expressions, such as function calls, will cause a parse error.
Example #7 Declaring static variables
As of PHP 8.1.0, when a method using static variables is inherited (but not overridden), the inherited method will now share static variables with the parent method. This means that static variables in methods now behave the same way as static properties.
Example #8 Usage of static Variables in Inherited Methods
Note : Static declarations are resolved in compile-time.
References with global and static variables
PHP implements the static and global modifier for variables in terms of references . For example, a true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. This can lead to unexpected behaviour which the following example addresses:
The above example will output:
A similar behaviour applies to the static statement. References are not stored statically:
This example demonstrates that when assigning a reference to a static variable, it's not remembered when you call the &get_instance_ref() function a second time.
User Contributed Notes 9 notes
Php advanced, mysql database, php examples, php reference, php operators.
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:
- Arithmetic operators
- Assignment operators
- Comparison operators
- Increment/Decrement operators
- Logical operators
- String operators
- Array operators
- Conditional assignment operators
PHP Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as addition, subtraction, multiplication etc.
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.
PHP Comparison Operators
The PHP comparison operators are used to compare two values (number or string):
PHP Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's value.
PHP Logical Operators
The PHP logical operators are used to combine conditional statements.
PHP String Operators
PHP has two operators that are specially designed for strings.
PHP Array Operators
The PHP array operators are used to compare arrays.
PHP Conditional Assignment Operators
The PHP conditional assignment operators are used to set a value depending on conditions:
Test yourself with exercises.
Multiply 10 with 5 , and output the result.
Start the Exercise
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Top references, top examples, get certified.