Reputation: 22018
I have used for years this method of testing for a $_POST var and assigning a value to $var simultaneously.
Today I ran into a server that seems to be different in its handling of this.
I'm loading the page http://site.com/foo.php?var=bar No form post made... and testing for $_POST var seems to unset my initial assignment
$var= $_GET['var'];
echo "var is $var\n"; // correctly echos $_GET['var']
if ($var= $_POST['foo']) {
echo "POST foo seen\n"; // does not fire, condition not met
}
echo "var is $var\n"; // does not echo $_GET['var']
When I switched to
if (isset($_POST['foo'])) {
$var = $_POST['foo'];
...
I got rid of the unsetting behavior.
So my question is whether this if ($var= $_POST['foo']) {
is bad form?
Upvotes: 0
Views: 220
Reputation: 95141
Try
$var = isset ( $_GET ['var'] ) ? $_GET ['var'] : null;
$foo = isset ( $_GET ['foo'] ) ? $_GET ['foo'] : null;
echo "var is $var\n"; // correctly echos $_GET['var']
if ($var === $foo) {
echo "POST foo seen\n"; // does not fire, condition not met
}
echo "var is $var\n"; //
Upvotes: 0
Reputation: 137492
You are using the assignment operator =
iinstead of the comparison operator ==
. Also, note that PHP will throw an E_STRICT
warning when accessing an undefined array element. Therefore, the best bet is typically:
$name = trim(isset($_POST['name']) ? $_POST['name'] : '');
or for integers:
$age = intval(isset($_POST['age']) ? $_POST['age'] : '');
Upvotes: 1