Popular Articles
- Echoing Content Directly (Aug 01, 2024)
- Sgml Style (Aug 01, 2024)
- Standard (Xml) Style (Aug 01, 2024)
- Embedding Php In Web Pages (Aug 01, 2024)
- Including Code (Aug 01, 2024)
Assignment Operators
Table of Contents
Introduction
Basic assignment operator, combined assignment operators, string and array assignment operators, the role of assignment operators in control structures, best practices and common mistakes.
PHP, a popular server-side scripting language, is fundamental for web development. Understanding how to manipulate data through expressions and operators is crucial for effective PHP programming. Assignment operators are particularly important as they allow you to set and modify the values of variables efficiently. For example, when managing user data in a form submission, assignment operators help store and update the input values seamlessly.
Introduction to assignment operators and their role in PHP
Assignment operators are used to assign values to variables. They come in various forms, each serving a unique purpose. From the basic = operator to more complex ones like += and .=, these operators simplify the process of handling variables and data. They are integral to PHP's functionality, especially in scenarios involving loops, conditional statements, and data manipulation.
The "=" operator
The basic assignment operator in PHP is the "=" sign. It is used to set the value of a variable.
How the basic assignment works in PHP
This operator assigns the value on the right to the variable on the left. It's the foundation of most operations in PHP, allowing values to be initialised and manipulated throughout the script.
Examples of basic assignment
- Assigning a string to a variable: $name = 'John';
- Assigning a number to a variable: $age = 30;
- Assigning the result of an arithmetic operation: $total = 20 + 15;
Overview of combined assignment operators
In PHP, combined assignment operators enhance coding efficiency by performing an operation and an assignment in a single step. These operators are syntactic sugar, reducing the complexity of common tasks in variable manipulation.
Operators and their functions
- += : Adds and assigns the value. $a = 5; $a += 3; // $a is now 8
- -= : Subtracts and assigns the value. $b = 5; $b -= 2; // $b is now 3
- *= : Multiplies and assigns the value. $c = 3; $c *= 4; // $c is now 12
- /= : Divides the variable by a value and assigns the result. $d = 10; $d /= 2; // $d is now 5
- %= : Performs division and assigns the remainder to the variable. $e = 10; $e %= 3; // $e is now 1
Real-world examples of using each combined operator
Combined assignment operators are particularly useful in scenarios involving iterative calculations or repeated updates to the same variable, such as calculating running totals or adjusting values in a loop.
- Using += for summing values in an array: $sum = 0; foreach ($numbers as $number) { $sum += $number; } // Output the sum echo $sum;
- Using *= in compound interest calculations: $principal = 1500; $rate = 0.05; $years = 10; for ($i = 0; $i < $years; $i++) { $principal *= (1 + $rate); } echo $principal;
Using .= for string concatenation
The .= operator in PHP is a powerful tool for appending one string onto another. This operator simplifies the process of building longer strings from multiple pieces, making it essential for tasks like generating dynamic HTML or processing form inputs.
Using += for array manipulation
While typically used for numerical addition, the += operator also has a significant role in arrays. It adds elements from one array to another but does not overwrite values at existing keys, unlike the array_merge function.
Practical examples demonstrating string and array assignments
- Building a dynamic URL query: $url = "http://example.com?"; $username = "user"; $token = "abc123"; $url .= "username=" . urlencode($username); $url .= "&token=" . urlencode($token); // Output: http://example.com?username=user&token=abc123
Note: In this example, since the += operator does not overwrite existing keys, the size remains 'medium', as defined in the defaults.
Use in loops (e.g., for, while)
Assignment operators are instrumental within loops for maintaining and updating the loop's control variables. This utility helps in optimizing the code and making it easier to manage and read.
- Incrementing a counter in a loop: for ($i = 0; $i < 10; $i++) { echo $i . ' '; } // Outputs: 0 1 2 3 4 5 6 7 8 9
- Accumulating total within a while loop: $i = 0; $total = 0; while ($i < 5) { $total += $i; $i++; } echo $total; // Outputs: 10
Use in conditional statements (if-else)
Assignment operators streamline operations within conditional statements, allowing variables to be updated based on different conditions efficiently.
- Adjusting values based on conditions: $age = 20; if ($age > 18) { $status = 'adult'; } else { $status = 'minor'; } echo $status; // Outputs: adult
- Modifying values in an associative array: $scores = ['John' => 75, 'Jane' => 85]; if ($scores['John'] < 80) { $scores['John'] += 5; // Increment John's score } // Outputs: ['John' => 80, 'Jane' => 85]
Example snippets showing assignment operators in control structures
These snippets illustrate how assignment operators facilitate the management of data within PHP's control structures, demonstrating their versatility and efficiency in various programming scenarios.
Assignment operators, while straightforward, require careful use to ensure code clarity and maintainability. Here are some tips to maximize their effectiveness:
- Always initialize variables before using them with assignment operators to avoid undefined behavior.
- Use combined assignment operators to make the code more concise and readable, especially within loops and conditional logic.
- Be mindful of operator precedence to ensure that expressions are evaluated in the order you intend.
Even seasoned developers can fall into traps when using assignment operators. Being aware of these can prevent common errors:
- Misusing the += operator with non-numeric data types: Remember that += is primarily for numerical calculations. Misapplying it to arrays or strings can lead to unexpected results.
- Overlooking the return value of an assignment: Assignments in PHP return the assigned value, which can be used in further expressions but sometimes leads to confusing code if not handled carefully.
- Confusing the == and = operators: It’s easy to mistakenly use = (assignment) instead of == (comparison) in conditional statements, which can lead to assignments where comparisons were intended.
Effective debugging strategies can save hours of troubleshooting. Here are some tailored for assignment operator issues:
- Check for unintentional assignments within conditional statements — a common source of bugs.
- Use debugging tools or simple echo statements to trace the changes in variable values throughout your script to understand where values may not be updating as expected.
- When dealing with complex expressions, break them down and test each component individually to isolate issues.
Recap of key points about assignment operators in PHP
Assignment operators are foundational to PHP programming, allowing developers to initialize, update, and manipulate variables efficiently. From the basic = operator to combined assignment operators like += and .=, understanding their proper use is crucial for writing clear and effective code.
Encouragement to practice using different types of assignment operators
The best way to master assignment operators is through consistent practice. By integrating these operators into various coding exercises and projects, you can enhance your fluency and confidence in using them. Try creating small scripts that leverage different assignment operators to see how they affect the flow and output of your code.
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:
Operator | Example | Equivalent | Operation |
---|---|---|---|
+= | $x += $y | $x = $x + $y | Addition |
-= | $x -= $y | $x = $x – $y | Subtraction |
*= | $x *= $y | $x = $x * $y | Multiplication |
/= | $x /= $y | $x = $x / $y | Division |
%= | $x %= $y | $x = $x % $y | Modulus |
**= | $z **= $y | $x = $x ** $y | Exponentiation |
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.
- Trending Categories
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
PHP return Statement
Introduction.
The purpose of return statement in PHP is to return control of program execution back to the environment from which it was called. Upon returning, execution of expression following the one which invooked other function or module.
If return statement occurs inside a function, execution of current function is terminated, handing over the control back to the environment from which it was called. The return statement may have an exprssion as optional clause in front of it. In that case, value of the expression is also returned in addition to the control.
If encountered in an included script, execution of current scripts ends immediately and control goes back to the script which has included it. If it is found in the top level script itself, the execution ends immdeiately, handding back the control to the OS.
return in a function
Following example shows return statement in a function
Live Demo
This will produce following result −
return with value
In following example, a function returns with an expression
In next example, test.php is included and has return ststement causing control go back to calling script.
This will produce following result when main script is run from command line−
There can be a expression clause in front of return statement in included file also. In following example, included test.php returns a string to main script that accepts and prints its value
- Related Articles
- PHP declare Statement
- PHP include_once Statement
- PHP require Statement
- PHP require_once Statement
- PHP goto Statement
- The return Statement in Python
- Return statement in Dart Programming
- Return statement in Lua Programming
- PHP Return by Reference
- How does JavaScript 'return' statement work?
- Can we have a return statement in a JavaScript switch statement?
- return statement vs exit() in main() C++
- PHP Interaction between finally and return
- Generator Return Expressions in PHP 7
- Which is faster, a MySQL CASE statement or a PHP if statement?
Kickstart Your Career
Get certified by completing the course
Assignment Operators in PHP : Tutorial
For Arrays "=>" operator is used to assign a value to a named key. |
Stack Exchange Network
Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
What is the benefit of having the assignment operator return a value?
I'm developing a language which I intend to replace both Javascript and PHP. (I can't see any problem with this. It's not like either of these languages have a large install base.)
One of the things I wanted to change was to turn the assignment operator into an assignment command, removing the ability to make use of the returned value.
I know that this would mean that those one-line functions that C people love so much would no longer work. I figured (with little evidence beyond my personal experience) that the vast majority of times this happened, it was really intended to be comparison operation.
Or is it? Are there any practical uses of the assignment operator's return value that could not be trivially rewritten? (For any language that has such a concept.)
- language-agnostic
- 12 JS and PHP do not have a large "install base"? – mhr Commented Feb 13, 2014 at 12:33
- 47 @mri I suspect sarcasm. – Andy Hunt Commented Feb 13, 2014 at 12:41
- 12 The only useful case I can remember is while((x = getValue()) != null) {} . Replacements will be uglier since you'll need to either use break or repeat the x = getValue assignment. – CodesInChaos Commented Feb 13, 2014 at 13:04
- 12 @mri Ooh no, I hear those two languages are just trivial things without any significant investment at all. Once the few people who insist on using JS see my language, they will switch over to mine and never have to write === again. I'm equally sure the browser makers will immediately roll out an update that includes my language alongside JS. :) – billpg Commented Feb 13, 2014 at 14:58
- 4 I would suggest to you that if your intention is to enhance an existing language and you intend it to be adopted widely then 100% backwards compatibility with the existing language is good. See TypeScript as an exemplar. If your intention is to provide a better alternative to an existing language then you have a much harder problem. A new language has to solve an existing realistic problem much much better than the existing language in order to pay for the cost of switching. Learning a language is an investment and it needs to pay off. – Eric Lippert Commented Feb 13, 2014 at 18:57
9 Answers 9
Technically, some syntactic sugar can be worth keeping even if it can trivially be replaced, if it improves readability of some common operation. But assignment-as-expression does not fall under that. The danger of typo-ing it in place of a comparison means it's rarely used (sometimes even prohibited by style guides) and provokes a double take whenever it is used. In other words, the readability benefits are small in number and magnitude.
A look at existing languages that do this may be worthwhile.
- Java and C# keep assignment an expression but remove the pitfall you mention by requiring conditions to evaluate to booleans. This mostly seems to work well, though people occasionally complain that this disallows conditions like if (x) in place of if (x != null) or if (x != 0) depending on the type of x .
- Python makes assignment a proper statement instead of an expression. Proposals for changing this occasionally reach the python-ideas mailing list, but my subjective impression is that this happens more rarely and generates less noise each time compared to other "missing" features like do-while loops, switch statements, multi-line lambdas, etc.
However, Python allows one special case, assigning to multiple names at once: a = b = c . This is considered a statement equivalent to b = c; a = b , and it's occasionally used, so it may be worth adding to your language as well (but I wouldn't sweat it, since this addition should be backwards-compatible).
- 5 +1 for bringing up a = b = c which the other answers do not really bring up. – Leo Commented Feb 13, 2014 at 15:53
- 6 A third resolution is to use a different symbol for assignment. Pascal uses := for assignment. – Brian Commented Feb 13, 2014 at 19:08
- 6 @Brian: Indeed, as does C#. = is assignment, == is comparison. – Marjan Venema Commented Feb 13, 2014 at 19:47
- 3 In C#, something like if (a = true) will throw a C4706 warning ( The test value in a conditional expression was the result of an assignment. ). GCC with C will likewise throw a warning: suggest parentheses around assignment used as truth value [-Wparentheses] . Those warnings can be silenced with an extra set of parentheses, but they are there to encourage explicitly indicating the assignment was intentional. – Bob Commented Feb 13, 2014 at 22:27
- 2 @delnan Just a somewhat generic comment, but it was sparked by "remove the pitfall you mention by requiring conditions to evaluate to booleans" - a = true does evaluate to a Boolean and is therefore not an error, but it also raises a related warning in C#. – Bob Commented Feb 13, 2014 at 23:48
Are there any practical uses of the assignment operator's return value that could not be trivially rewritten?
Generally speaking, no. The idea of having the value of an assignment expression be the value that was assigned means that we have an expression which may be used for both its side effect and its value , and that is considered by many to be confusing.
Common usages are typically to make expressions compact:
has the semantics in C# of "convert z to the type of y, assign the converted value to y, the converted value is the value of the expression, convert that to the type of x, assign to x".
But we are already in the realm of impertative side effects in a statement context, so there's really very little compelling benefit to that over
Similarly with
being a shorthand for
Again, in the original code we are using an expression both for its side effects and its value, and we are making a statement that has two side effects instead of one. Both are smelly; try to have one side effect per statement, and use expressions for their values, not for their side effects.
I'm developing a language which I intend to replace both Javascript and PHP.
If you really want to be bold and emphasize that assignment is a statement and not an equality, then my advice is: make it clearly an assignment statement .
There, done. Or
or even better:
Or even better still
There's absolutely no way that any of those are going to be confused with x == 1 .
- 1 Is the world ready for non-ASCII Unicode symbols in programming languages? – billpg Commented Feb 14, 2014 at 11:25
- As much as I would love what you suggest, one of my goals is that most "well written" JavaScript can be ported over with little or no modification. – billpg Commented Feb 14, 2014 at 11:44
- 2 @billpg: Is the world ready ? I don't know -- was the world ready for APL in 1964, decades before the invention of Unicode? Here's a program in APL that picks a random permutation of six numbers out of the first 40: x[⍋x←6?40] APL required its own special keyboard, but it was a pretty successful language. – Eric Lippert Commented Feb 14, 2014 at 15:17
- @billpg: Macintosh Programmer's Workshop used non-ASCII symbols for things like regex tags or redirection of stderr. On the other hand, MPW had the advantage that the Macintosh made it easy to type non-ASCII characters. I must confess some puzzlement as to why the US keyboard driver doesn't provide any decent means of typing any non-ASCII characters. Not only does Alt-number entry require looking up character codes--in many applications it doesn't even work. – supercat Commented Feb 14, 2014 at 18:20
- Hm, why would one prefer to assign "to the right" like a+b*c --> x ? This looks strange to me. – Ruslan Commented Aug 21, 2015 at 10:49
Many languages do choose the route of making assignment a statement rather than an expression, including Python:
and Golang:
Other languages don't have assignment, but rather scoped bindings, e.g. OCaml:
However, let is an expression itself.
The advantage of allowing assignment is that we can directly check the return value of a function inside the conditional, e.g. in this Perl snippet:
Perl additionally scopes the declaration to that conditional only, which makes it very useful. It will also warn if you assign inside a conditional without declaring a new variable there – if ($foo = $bar) will warn, if (my $foo = $bar) will not.
Making the assignment in another statement is usually sufficient, but can bring scoping problems:
Golang heavily relies on return values for error checking. It therefore allows a conditional to take an initialization statement:
Other languages use a type system to disallow non-boolean expressions inside a conditional:
Of course that fails when using a function that returns a boolean.
We now have seen different mechanisms to defend against accidental assignment:
- Disallow assignment as an expression
- Use static type checking
- Assignment doesn't exist, we only have let bindings
- Allow an initialization statement, disallow assignment otherwise
- Disallow assignment inside a conditional without declaration
I've ranked them in order of ascending preference – assignments inside expressions can be useful (and it's simple to circumvent Python's problems by having an explicit declaration syntax, and a different named argument syntax). But it's ok to disallow them, as there are many other options to the same effect.
Bug-free code is more important than terse code.
- +1 for "Disallow assignment as an expression". The use-cases for assignment-as-an-expression don't justify the potential for bugs and readability issues. – poke Commented Feb 14, 2014 at 17:00
You said "I figured (with little evidence beyond my personal experience) that the vast majority of times this happened, it was really intended to be comparison operation."
Why not FIX THE PROBLEM?
Instead of = for assignment and == for equality test, why not use := for assignment and = (or even ==) for equality?
If you want to make it harder for the programmer to mistake assignment for equality, then make it harder.
At the same time, if you REALLY wanted to fix the problem, you would remove the C crock that claimed booleans were just integers with predefined symbolic sugar names. Make them a different type altogether. Then, instead of saying
you force the programmer to write:
The fact is that assignment-as-an-operator is a very useful construct. We didn't eliminate razor blades because some people cut themselves. Instead, King Gillette invented the safety razor.
- 2 (1) := for assignment and = for equality might fix this problem, but at the cost of alienating every programmer who didn't grow up using a small set of non-mainstream languages. (2) Types other than bools being allows in conditions isn't always due to mixing up bools and integers, it's sufficient to give a true/false interpretation to other types. Newer language that aren't afraid to deviate from C have done so for many types other than integers (e.g. Python considers empty collections false). – user7043 Commented Feb 13, 2014 at 13:38
- 1 And regarding razor blades: Those serve a use case that necessitates sharpness. On the other hand, I'm not convinced programming well requires assigning to variables in the middle of an expression evaluation. If there was a simple, low-tech, safe and cost efficient way to make body hair disappear without sharp edges, I'm sure razor blades would have been displaced or at least made much more rare. – user7043 Commented Feb 13, 2014 at 13:40
- 1 @delnan: A wise man once said "Make it as simple as possible, but no simpler." If your objective is to eliminate the vast majority of a=b vs. a==b errors, restricting the domain of conditional tests to booleans and eliminating the default type conversion rules for <other>->boolean gets you just about all the way there. At that point, if(a=b){} is only syntactically legal if a and b are both boolean and a is a legal lvalue. – John R. Strohm Commented Feb 13, 2014 at 15:07
- Making assignment a statement is at least as simple as -- arguably even simpler than -- the changes you propose, and achieves at least as much -- arguably even more (doesn't even permit if (a = b) for lvalue a, boolean a, b). In a language without static typing, it also gives much better error messages (at parse time vs. run time). In addition, preventing "a=b vs. a==b errors" may not be the only relevant objective. For example, I'd also like to permit code like if items: to mean if len(items) != 0 , and that I'd have to give up to restrict conditions to booleans. – user7043 Commented Feb 13, 2014 at 15:14
- 1 @delnan Pascal is a non-mainstream language? Millions of people learned programming using Pascal (and/or Modula, which derives from Pascal). And Delphi is still commonly used in many countries (maybe not so much in yours). – jwenting Commented Feb 14, 2014 at 9:39
To actually answer the question, yes there are numerous uses of this although they are slightly niche.
For example in Java:
The alternative without using the embedded assignment requires the ob defined outside the scope of the loop and two separate code locations that call x.next().
It's already been mentioned that you can assign multiple variables in one step.
This sort of thing is the most common use, but creative programmers will always come up with more.
- Would that while loop condition deallocate and create a new ob object with every loop? – user3932000 Commented May 3, 2017 at 22:33
- @user3932000 In that case probably not, usually x.next() is iterating over something. It is certainly possible that it could though. – Tim B Commented May 4, 2017 at 8:18
- I can't get the above to compile unless I declare the variable beforehand and remove the declaration from inside. It says Object cannot be resolved to a variable. – William Jarvis Commented Apr 15, 2021 at 16:42
Since you get to make up all the rules, why now allow assignment to turn a value, and simply not allow assignments inside conditional steps? This gives you the syntactic sugar to make initializations easy, while still preventing a common coding mistake.
In other words, make this legal:
But make this illegal:
- 2 That seems like a rather ad-hoc rule. Making assignment a statement and extending it to allow a = b = c seems more orthogonal, and easier to implement too. These two approach disagree about assignment in expressions ( a + (b = c) ), but you haven't taken sides on those so I assume they don't matter. – user7043 Commented Feb 13, 2014 at 13:01
- "easy to implement" shouldn't be much of a consideration. You are defining a user interface -- put the needs of the users first. You simply need to ask yourself whether this behavior helps or hinders the user. – Bryan Oakley Commented Feb 13, 2014 at 13:05
- if you disallow implicit conversion to bool then you don't have to worry about assignment in conditions – ratchet freak Commented Feb 13, 2014 at 13:08
- Easier to implement was only one of my arguments. What about the rest? From the UI angle, I might add that IMHO incoherent design and ad-hoc exceptions generally hinders the user in grokking and internalising the rules. – user7043 Commented Feb 13, 2014 at 13:10
- @ratchetfreak you could still have an issue with assigning actual bools – jk. Commented Feb 13, 2014 at 13:25
By the sounds of it, you are on the path of creating a fairly strict language.
With that in mind, forcing people to write:
instead of:
might seem an improvement to prevent people from doing:
when they meant to do:
but in the end, this kind of errors are easy to detect and warn about whether or not they are legal code.
However, there are situations where doing:
does not mean that
will be true.
If c is actually a function c() then it could return different results each time it is called. (it might also be computationally expensive too...)
Likewise if c is a pointer to memory mapped hardware, then
are both likely to be different, and also may also have electronic effects on the hardware on each read.
There are plenty of other permutations with hardware where you need to be precise about what memory addresses are read from, written to and under specific timing constraints, where doing multiple assignments on the same line is quick, simple and obvious, without the timing risks that temporary variables introduce
- 4 The equivalent to a = b = c isn't a = c; b = c , it's b = c; a = b . This avoids duplication of side effects and also keeps the modification of a and b in the same order. Also, all these hardware-related arguments are kind of stupid: Most languages are not system languages and are neither designed to solve these problems nor are they being used in situations where these problems occur. This goes doubly for a language that attempts to displace JavaScript and/or PHP. – user7043 Commented Feb 13, 2014 at 13:04
- delnan, the issue wasn't are these contrived examples, they are. The point still stands that they show the kinds of places where writing a=b=c is common, and in the hardware case, considered good practice, as the OP asked for. I'm sure they will be able to consider their relevance to their expected environment – Michael Shaw Commented Feb 13, 2014 at 13:51
- Looking back, my problem with this answer is not primarily that it focuses on system programming use cases (though that would be bad enough, the way it's written), but that it rests on assuming an incorrect rewriting. The examples aren't examples of places where a=b=c is common/useful, they are examples of places where order and number of side effects must be taken care of. That is entirely independent. Rewrite the chained assignment correctly and both variants are equally correct. – user7043 Commented Feb 13, 2014 at 13:58
- @delnan: The rvalue is converted to the type of b in one temp, and that is converted to the type of a in another temp. The relative timing of when those values are actually stored is unspecified. From a language-design perspective, I would think it reasonable to require that all lvalues in a multiple-assignment statement have matching type, and possibly to require as well that none of them be volatile. – supercat Commented Feb 13, 2014 at 19:17
The greatest benefit to my mind of having assignment be an expression is that it allows your grammar to be simpler if one of your goals is that "everything is an expression"--a goal of LISP in particular.
Python does not have this; it has expressions and statements, assignment being a statement. But because Python defines a lambda form as being a single parameterized expression , that means you can't assign variables inside a lambda. This is inconvenient at times, but not a critical issue, and it's about the only downside in my experience to having assignment be a statement in Python.
One way to allow assignment, or rather the effect of assignment, to be an expression without introducing the potential for if(x=1) accidents that C has is to use a LISP-like let construct, such as (let ((x 2) (y 3)) (+ x y)) which might in your language evaluate as 5 . Using let this way need not technically be assignment at all in your language, if you define let as creating a lexical scope. Defined that way, a let construct could be compiled the same way as constructing and calling a nested closure function with arguments.
On the other hand, if you are simply concerned with the if(x=1) case, but want assignment to be an expression as in C, maybe just choosing different tokens will suffice. Assignment: x := 1 or x <- 1 . Comparison: x == 1 . Syntax error: x = 1 .
- 1 let differs from assignment in more ways than technically introducing a new variable in a new scope. For starters, it has no effect on code outside the let 's body, and therefore requires nesting all code (what should use the variable) further, a significant downside in assignment-heavy code. If one was to go down that route, set! would be the better Lisp analogue - completely unlike comparison, yet not requiring nesting or a new scope. – user7043 Commented Feb 13, 2014 at 21:36
- @delnan: I'd like to see a combination declare-and-assign syntax which would prohibit reassignment but would allow redeclaration, subject to the rules that (1) redeclaration would only be legal for declare-and-assign identifiers, and (2) redeclaration would "undeclare" a variable in all enclosing scopes. Thus, the value of any valid identifier would be whatever was assigned in the previous declaration of that name. That would seem a little nicer than having to add scoping blocks for variables that are only used for a few lines, or having to formulate new names for each temp variable. – supercat Commented Feb 14, 2014 at 3:08
Indeed. This is nothing new, all the safe subsets of the C language have already made this conclusion.
MISRA-C, CERT-C and so on all ban assignment inside conditions, simply because it is dangerous.
There exists no case where code relying on assignment inside conditions cannot be rewritten.
Furthermore, such standards also warns against writing code that relies on the order of evaluation. Multiple assignments on one single row x=y=z; is such a case. If a row with multiple assignments contains side effects (calling functions, accessing volatile variables etc), you cannot know which side effect that will occur first.
There are no sequence points between the evaluation of the operands. So we cannot know whether the subexpression y gets evaluated before or after z : it is unspecified behavior in C. Thus such code is potentially unreliable, non-portable and non-conformant to the mentioned safe subsets of C.
The solution would have been to replace the code with y=z; x=y; . This adds a sequence point and guarantees the order of evaluation.
So based on all the problems this caused in C, any modern language would do well to both ban assignment inside conditions, as well as multiple assignments on one single row.
Not the answer you're looking for? Browse other questions tagged language-agnostic syntax operators or ask your own question .
- The Overflow Blog
- Masked self-attention: How LLMs learn relationships between tokens
- Deedy Das: from coding at Meta, to search at Google, to investing with Anthropic
- Featured on Meta
- User activation: Learnings and opportunities
- Preventing unauthorized automated access to the network
Hot Network Questions
- In a shell script, how do i wait for a volume to be available?
- How to reject non-physical solutions to the wave equation?
- In John 3:16, what is the significance of Jesus' distinction between the terms 'world' and 'everyone who believes' within the context?
- Does the A320 have an audible A/THR disconnect sound?
- What "Texas and federal law"s is SpaceX "in violation of"?
- What does "we are out"mean here?
- Used car dealership refused to let me use my OBDII on their car, is this a red flag?
- Is my TOTP key secure on a free hosting provider server with FTP and .htaccess restrictions?
- Did Classical Latin authors ever incorrectly utilize an Ablative of Location for nouns that utilize the Locative Case?
- What are major reasons why Republicans support the death penalty?
- Neil Tyson: gravity is the same every where on the geoid
- Are logic and mathematics the only fields in which certainty (proof) can be obtained?
- If a 'fire temple' was built in a gigantic city, with many huge perpetual flames inside, how could they keep smoke from bothering non-worshippers?
- Why would an ocean world prevent the creation of ocean bases but allow ships?
- Find the side lengths of a right triangle in terms of the distances of a point from its vertices,
- How to Organise/Present Built Worlds?
- How to jointly estimate range and delay of a target?
- Remove an entire inner list that has any zeros
- What does Simone mean by "an animal born in a butcher's shop" when referring to her "ponce" in Mona Lisa?
- What is "illegal, immoral or improper" use in CPOL?
- How similar were the MC6800 and MOS 6502?
- C3h point group
- How can I write A2:A and not get any results for empty cells
- Is it possible to know where the Sun is just by looking at the Moon?
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.
- Function Reference
- Variable and Type Related Extensions
- Array Functions
(PHP 4, PHP 5, PHP 7, PHP 8)
list — Assign variables as if they were an array
Description
Like array() , this is not really a function, but a language construct. list() is used to assign a list of variables in one operation. Strings can not be unpacked and list() expressions can not be completely empty.
Note : Before PHP 7.1.0, list() only worked on numerical arrays and assumes the numerical indices start at 0.
A variable.
Further variables.
Return Values
Returns the assigned array.
Version | Description |
---|---|
7.3.0 | Support for reference assignments in array destructuring was added. |
7.1.0 | It is now possible to specify keys in . This enables destructuring of arrays with non-integer or non-sequential keys. |
Example #1 list() examples
Example #2 An example use of list()
Example #3 Using nested list()
Example #4 list() and order of index definitions
The order in which the indices of the array to be consumed by list() are defined is irrelevant.
Gives the following output (note the order of the elements compared in which order they were written in the list() syntax):
Example #5 list() with keys
As of PHP 7.1.0 list() can now also contain explicit keys, which can be given as arbitrary expressions. Mixing of integer and string keys is allowed; however, elements with and without keys cannot be mixed.
The above example will output:
- each() - Return the current key and value pair from an array and advance the array cursor
- array() - Create an array
- extract() - Import variables into the current symbol table from an array
Improve This Page
User contributed notes 24 notes.
PHP Tutorial
Php advanced, mysql database, php examples, php reference, php form handling.
The PHP superglobals $_GET and $_POST are used to collect form-data.
PHP - A Simple HTML Form
The example below displays a simple HTML form with two input fields and a submit button:
When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables.
The "welcome.php" looks like this:
The output could be something like this:
The same result could also be achieved using the HTTP GET method:
Same example, but the method is set to GET instead of POST:
and "welcome_get.php" looks like this:
The code above is quite simple, and it does not include any validation.
You need to validate form data to protect your script from malicious code.
Think SECURITY when processing PHP forms!
This page does not contain any form validation, it just shows how you can send and retrieve form data.
However, the next pages will show how to process PHP forms with security in mind! Proper validation of form data is important to protect your form from hackers and spammers!
Advertisement
GET vs. POST
Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2, key3 => value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
When to use GET?
Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.
GET may be used for sending non-sensitive data.
Note: GET should NEVER be used for sending passwords or other sensitive information!
When to use POST?
Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.
Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
Developers prefer POST for sending form data.
Next, lets see how we can process PHP forms the secure way!
COLOR PICKER
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.
PHP assignment return value [closed]
Assuming that you can do (new Object)->method() in PHP5.4+ I was wondering why I cannot do this:
Why the last line of code triggers PHP Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR)
It looks like I need to clarify my question, as I see answers completely not related to my question. I'm not asking how to get rid of syntax error. My question is: Why I cannot access property on expression ($object = (new Container())->getItem()) , while get_class() tells me that this is an instance of Item?
- syntax-error
- Even if it's possible, why do you want to ? – HamZa Commented Oct 18, 2013 at 13:10
- And what about this: echo (new Container())->getItem()->property; ??? Or to make it working with Your assingment: echo $property = (new Container())->getItem()->property; – shadyyx Commented Oct 18, 2013 at 13:11
- @HamZa I don't want to do, I just wonder why get_class tells me that I have an object of class Item, but I cannot access its property. – Janusz Slota Commented Oct 18, 2013 at 13:13
- 4 This question appears to be off-topic because it is about syntax error. – tereško Commented Oct 18, 2013 at 13:23
2 Answers 2
You can only dereference function return values in PHP 5.4 (I believe in 5.5 you can dereference newly-created arrays like ['x','y','z'][$index] )
Since assignment is not a function, you can't dereference it.
- Can you provide more details please? According to PHP manual : The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3. Which I presume the value of ($object = (new Container())->getItem()) is equivalent to $object . This is what get_class says. – Janusz Slota Commented Oct 18, 2013 at 14:23
- 2 Dereferencing is a special syntax, which takes place during the parsing phase (before ANY code is executed). The parser cannot "see" that the assignment is something that can be dereferenced, because that depends on things that happen at run-time. – Niet the Dark Absol Commented Oct 18, 2013 at 14:24
Why not use an extended class?
This has been available since PHP4
Manual For Extends
Or if you wish to initialize the object from OOP Scope:
Not the answer you're looking for? Browse other questions tagged php syntax-error or ask your own question .
- The Overflow Blog
- Masked self-attention: How LLMs learn relationships between tokens
- Deedy Das: from coding at Meta, to search at Google, to investing with Anthropic
- Featured on Meta
- User activation: Learnings and opportunities
- Preventing unauthorized automated access to the network
- Feedback Requested: How do you use the tagged questions page?
Hot Network Questions
- What does "we are out"mean here?
- Can I use named pipes to achieve temporal uncoupling?
- Is it ethical to edit grammar, spelling, and wording errors in survey questions after the survey has been administered, prior to publication?
- Do pilots have to produce their pilot license to police when asked?
- Krull dimension in non-algebraically closed fields
- Neil Tyson: gravity is the same every where on the geoid
- Help with unidentified character denoting temperature, 19th century thermodynamics
- What is the name for this BC-BE back-to-back transistor configuration?
- Why is my Lenovo ThinkPad running Ubuntu using the e1000e Ethernet driver?
- Randomly color the words
- What "Texas and federal law"s is SpaceX "in violation of"?
- Is it possible to know where the Sun is just by looking at the Moon?
- Matter made of neutral charges does not radiate?
- Five Hundred Cigarettes
- Taking out the film from the roll can it still work?
- Can I redeem myself with a better research paper if my thesis sucks?
- Strange Occurrences When Using Titlesec and Section Title Begins with `L'
- Does the A320 have an audible A/THR disconnect sound?
- In John 3:16, what is the significance of Jesus' distinction between the terms 'world' and 'everyone who believes' within the context?
- Where is this NPC's voice coming from?
- What happened with the 31.5 ft giant in Jubbulpore district (now Jabalpur), India, August 8, 1934?
- How to fix bottom of stainless steel pot that has been separated from its main body?
- Why would an ocean world prevent the creation of ocean bases but allow ships?
- How to jointly estimate range and delay of a target?
IMAGES
VIDEO
COMMENTS
Now, I'm aware that I can simply perform the assignment before the return statement, but this is just a contrived example, and I'm curious as to the feasibility. Edit : Providing a little more clarification.
PHP is a popular general-purpose scripting language that powers everything from your blog to the most popular websites in the world. Downloads; ... 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.
If I wanted to write a function that could be treated this way, do I have to do anything special, other than return false on certain conditions? php; variable-assignment; evaluation; Share. Follow asked May 9, 2011 at 17:56. user151841 ... When you do an assignment in PHP, the assignment returns the value that was assigned. This allows you to ...
return returns program control to the calling module. Execution resumes at the expression following the called module's invocation. If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call. return also ends the execution of an eval ...
The return keyword ends a function and, optionally, uses the result of an expression as the return value of the function. If return is used outside of a function, it stops PHP code in the file from running. If the file was included using include, include_once, require or require_once, the result of the expression is used as the return value of ...
Overlooking the return value of an assignment: Assignments in PHP return the assigned value, which can be used in further expressions but sometimes leads to confusing code if not handled carefully. Confusing the == and = operators: It's easy to mistakenly use = (assignment) instead of == (comparison) in conditional statements, which can lead ...
PHP is a popular general-purpose scripting language that powers everything from your blog to the most popular websites in the world. ... Values are returned by using the optional return statement. Any type may be returned, including arrays and objects. This causes the function to end its execution immediately and pass control back to the line ...
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.
Introduction. The purpose of return statement in PHP is to return control of program execution back to the environment from which it was called. Upon returning, execution of expression following the one which invooked other function or module. If return statement occurs inside a function, execution of current function is terminated, handing ...
= is the Assignment Operator in PHP .For Arrays => operator is used to assign a value to a named key. PHP Tutorials and Lessons : Code2care . Introduction to PHP: Tags: Comments: ... Return statement: Include, include_once: Require, require_once: Goto + Functions + PHP Classes & Objects:
I haven't seen anyone note method chaining in PHP5. When an object is returned by a method in PHP5 it is returned by default as a reference, and the new Zend Engine 2 allows you to chain method calls from those returned objects.
PHP User Defined Functions. Besides the built-in PHP functions, it is possible to create your own functions. A function is a block of statements that can be used repeatedly in a program. A function will not execute automatically when a page loads. A function will be executed by a call to the function.
Furthermore, such standards also warns against writing code that relies on the order of evaluation. Multiple assignments on one single row x=y=z; is such a case. If a row with multiple assignments contains side effects (calling functions, accessing volatile variables etc), you cannot know which side effect that will occur first.
In PHP, the reference assignment operator (=&) is used to create a new variable as an alias to an existing spot in memory. ... 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, ...
PHP is a popular general-purpose scripting language that powers everything from your blog to the most popular websites in the world. ... In PHP, the || operator only ever returns a boolean. For a chainable assignment operator, use the ?: "Elvis" operator. JavaScript: let a = false; let b = false; let c = true; let d = false; ... return 'banana ...
The 28-year-old Garrett hadn't played in the majors since breaking his left leg while trying to rob the New York Yankees' DJ LeMahieu of a home run on Aug. 23, 2023.
One of the key-points of PHP OOP that is often mentioned is that "objects are passed by references by default". This is not completely true. This section rectifies that general thought using some examples. A PHP reference is an alias, which allows two different variables to write to the same value. In PHP, an object variable doesn't contain the ...
The rule is to return the right-hand operand of = converted to the type of the variable which is assigned to. int a; float b; a = b = 4.5; // 4.5 is a double, it gets converted to float and stored into b. // this returns a float which is converted to an int and stored in a. // the whole expression returns an int.
PHP is a popular general-purpose scripting language that powers everything from your blog to the most popular websites in the world. ... Support for reference assignments in array destructuring was added. 7.1.0: It is now possible to specify keys in ... - Return the current key and value pair from an array and advance the array cursor; array ...
Example Get your own PHP Server. When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method. To display the submitted data you could simply echo all the variables. The "welcome.php" looks like this:
PHP assignment return value [closed] Ask Question Asked 10 years, 10 months ago. Modified 10 years, 10 months ago. Viewed 224 times Part of PHP Collective 1 Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers. ...