Web Hosting Talk







View Full Version : [php] Is this code bad?


Georgecooldude
09-27-2004, 11:31 AM
$code1X - $locationX = $result1Y


I am trying to add the numeric values of $code1X and $locationX and save the result into another variable. I am not sure if it is correct code. Could someone say if its right or wrong. :)

azizny
09-27-2004, 11:36 AM
Try this:

<?
$result1Y = $code1X - $locationX
?>


Peace,

TablesandChairs4
09-27-2004, 05:21 PM
I don't think any languages (at least, that I've seen) go in that order. Always have the variable you're setting the value on the left, and what to set it as on the right, like azizny's code.

Burhan
09-28-2004, 03:01 AM
Some clarification here.

This statement:

<?php $x - $y = $z; ?>


Is syntactically correct, and the PHP interpreter will not give you any errors. However, it does not do as you would expect because of operator precedence.

The = operator is right associative, which means it evaluates from right to left, then it will do the minus operation.

So, it will first assign $y the value of $z, then take the result of that and subtract it from $x.

An easier way to see what is going on is this :

$x - ($y = $z);

Here are some examples to illustrate the point, and to clear things up :)

<?php

$x = 5;
$y = 2;
$z = 0;

echo "Starting values :\n";
var_dump($x);
var_dump($y);
var_dump($z);

$x - $y = $z;
echo 'After : $x - $y = $z '; echo "\n";
var_dump($x);
var_dump($y);
var_dump($z);

$x - ($y = $z);
echo 'After : $x - ($y = $z) '; echo "\n";
var_dump($x);
var_dump($y);
var_dump($z);

$z = $x - $y;
echo 'After $z = $x - $y '; echo "\n";
var_dump($x);
var_dump($y);
var_dump($z);

$z = ($x - $y);
echo 'After $z = ($x - $y) '; echo "\n";
var_dump($x);
var_dump($y);
var_dump($z);

$t = $x + $y;
echo 'After $t = $x - $y '; echo "\n";

var_dump($x);
var_dump($y);
var_dump($z);
var_dump($t);

?>


Output:

Starting values :
int(5)
int(2)
int(0)
After : $x - $y = $z
int(5)
int(0)
int(0)
After : $x - ($y = $z)
int(5)
int(0)
int(0)
After $z = $x - $y
int(5)
int(0)
int(5)
After $z = ($x - $y)
int(5)
int(0)
int(5)
After $t = $x - $y
int(5)
int(0)
int(5)
int(5)


See this table (http://www.php.net/manual/en/language.operators.php#language.operators.precedence) for information on operator precedence.

Georgecooldude
09-28-2004, 06:47 AM
fyrestrtr,

This is good to know and helps me in my programming.

Thankyou!!

:D