User Contributed Notes 연산자 (Operators) |
add a note |
stanis at sibfair dot nsk dot su
28-Mar-2000 07:47 |
|
In case you are just beginning to code in PHP and this is your first
experience in programming, the Modulus (%) is a great way to code photo
albums based on a table (it returns the remainder of integer divided by
integer). The modulus helps to wrap data to next row based on the result
of '$currentrow(from db)' % 'number of columns in database'. The only
thing to look out for is that 1 % 4 is 1, 2 % 4 is 2, etc. and not zero or
some other number, like you might think at first. Hope this will help some
newbie programmers like myself.
|
|
kennon at audiogalaxy dot com
15-Aug-2000 01:41 |
|
You can also use the floor() and ceil() functions to give the nearest
integer values of a double. So, for instance, to get the integer part of
the quotient, you can do this:
floor( $a / $b );
|
|
kees at tweakers dot net
04-Jan-2001 02:54 |
|
Normally, a negative value modulo a positive number generates a negaive
number, if you don't want that (for example, the number has to be between
0 and 9 and not negative) then you can use a function like
this:
function mod($a,$b)
{
if ($a <= 0) return (int)
mod($b-abs($a), $b); else return (int) $a % $b;
}
for example:
-2 % 10 = -2
but mod(-2, 10) will return 8.
|
|
bdiaz at aullox dot com
25-Jan-2001 02:57 |
|
Yet another IWBNI posting...
I used the caret ( ^ )
"operator" in a truncate() function of mine with a result
similar to a substraction. So, I had to implement an even weirder function
which would work better. Should anyone know of a better way to do this, I
thank in advance.
//The function expects a double $num and an int
$pos indicating the decimal
//positions to allow
function
truncate($num,$pos){
$pos=(int)$pos;
$m="1e$pos"; //this
is our divider, ten at $pos power
$t=(double)$num*(double)$m; //just
to be sure
$t=(int)$t; //yes, we need to cut superfluous
decimals
$t=(double)$t/(double)$m;
return $t;
}
|
|
yasuo_ohgaki at hotmail dot com
09-Mar-2001 08:38 |
|
There are some operator descriptions missing. (I'm not sure what is
considered as operator in PHP, but anyway)
::
Scope
resolution operator for class
->
Member selection operator
for class
new
Object creation operator
?:
It is
described in Comparison Operator Section. I think it worth to make a new
sub section for ternary operator.
[]
I think Array
"[]" is considered as operator. It mentioned in Operator
Precedence Section as [, but no description. (Or is there any other use
for single "["?)
()
Grouping expressions. It might
not considered as operator in PHP, but it is better to be included at
least in Operator Precedence section.
{}
Resolve ambiguous
reference to variables. For example, {} is needed to resolve
$array1['array_stored_as_array_element']['value']. {} is also needed to
resolve ambiguity such as echo " $array_3d[1][2][3] "
It
might not considered as operator in PHP, but it is better to be included
at least in Operator Precedence section.
&
Reference
operator. There is a section for reference, but it is better to be
explained briefly in this section and direct reader to Reference
section.
(type)
Cast operator like (int)$v to get integer
value. I suppose these are operators also. Mentioned in Precedence
section, but no description.
+= -= *= /= .= %= &= |= ^= ~=
<<= >>=
Some assignment operators that are supported are
not described. Mentioned in Precedence section,
though.
print
Looks like "print" is considered as
operator in PHP. (I thought "echo" is) It mentioned in
Precedence section, but no description. Description for these may be
helpful for programmers to distinguish what is "expression" and
what is not.
For some reason, PHP4.0.4pl1 dose not allow. (I
posted as bug, I got reply "echo" is not a valid expression.
Therefore, PHP complained for following code as a parse
error)
($val) ? echo('true') : echo('false');
but PHP
does ALLOW
($val) ? print('true') : print('false');
($val) ?
include('true.inc') : include('false.inc');
I'm confused with
these. i.e. What is a expression, what is not an expression.
If
there are other operators like "print" (maybe echo?), all of
them should be described or mentioned, at least, in this section. (I think
it would be nice to have a section describing what is statements/language
construct)
It is not about operator, but it would be nice to have
BNF of PHP (Zend Script Engine) as a reference.
|
|
jeroen at php dot net
31-Jul-2001 09:38 |
|
There is no power-operator. Use pow() instead.
See:
There
might come a power-operator in a future release, but that is still being
discussed
|
|
mahmoud.at.infoscience.it
12-Dec-2001 04:24 |
|
You can use the shorthand:
$a = 5;
$a += 10; // $a is now
15
$a -= 3; // $a is now 12
|
|
php.at.michrev.com
08-Mar-2002 09:42 |
|
If this doesn't work: ($val) ? echo('true') : echo('false'); ...you
should use this: if($val) { echo('true'); } else { echo('false');
} ...or, better yet, this: echo($val ? 'true' :
'false'); ...because $val, 'true', and 'false' are all expressions, but
echo() is not.
The "expr?expr:expr" operator is used to
select between expressions in the middle of a command. If you need to
select between different commands instead, it's probably better to use
if() instead. That's what it's there for.
|
|
ronm1958 at adelphia dot net
15-Apr-2002 04:59 |
|
The PHP modulus function will (interestingly) not return the decimal
portion of the result. I wrote a little function that will do so, and
mimics the results obtained by using the Windows calculator mod
function:
function modphp($x, $y, $z) {
for ($y = 0; $y
<= abs($z); $y++) { $w = abs($z) - (abs($x) * $y); if ($w
< abs($x)) { break; } }
if ($z < 0)
{ return(-$w); } else
{ return($w); }
}
Here's how to pull the answer out
of the mod function above:
$answer = modphp($var_x, $var_y,
$var_z);
|
|
msopacua at idg dot nl
09-Jun-2002 12:56 |
|
Remember that when you're reading from a socket, all output is of type
string.
Use ord() on each 'character', to get the byte values and
use bitwise arithmetics.
|
|
18-Jun-2002 11:21 |
|
The =& operator can be found in section 14 -- returning references.
|
|
zontar at mindless dot com
04-Aug-2002 11:53 |
|
It appears that the shortcut logical operators &&= and ||= are not
supported. Drag. :(
|
|
28-Aug-2002 09:43 |
|
It should be noted that PHP's ?: operator associates left to right. In C
and in C++, the ?: operator associates right to left. Thus:
1 ? 2
: 3 ? 4 : 5;
has the value 4 in PHP and the value 2 in C and in
C++. I find it curious that they would reverse the associativity of an
operator from its "accepted" sense, but yet they didn't fix the
precedence of the bitwise operators. Thus:
if(A & 7 ==
5)
groups like:
if(A & (7 == 5))
It is a trap for
the unlucky.
|
|
rick at brainscraps dot com
16-Nov-2002 10:55 |
|
To add to Yasuo's detailed information above, I have seen no mention of
'=>', which is used for:
1. Associative array creation (),
$myarray
= array("name"=>"Rick",
"age"=>"No answer");
2. Associating keys and
values in foreach() ()
foreach($myarray as $key=>$value){ echo "my $key is
$value \n"; }
I don't know... I guess this could properly
be called an array dereferencer (?), but wouldn't it make sense to include
this among the assignment operators?
|
|
eric at themepark dot com
16-Dec-2002 03:46 |
|
note that the ternary operator comes BEFORE the "." (string
concatenate) operator... so
$a = 'eric is a '.(1) ? 'goofball' :
'kitty-cat'; echo $a;
this snippet returns "goofball"
instead of "eric is a goofball".
$a = 'eric is a '.((1) ?
'goofball' : 'kitty-cat'); echo $a;
This snippet returns
"eric is a goofball".
this little oversight bit me on the
metaphorical ass :-) so hopefully this'll help others...
|
|
jlsalinas at gmx dot SPAMSUCKS dot net
11-Jan-2003 05:11 |
|
About Rick's comment on 16-Nov-2002:
=> cannot be an operator,
for it would be impossible to specify keys when building arrays. Supposing
that => is an operator, bluiding $arr this way:
$arr = array
('key1' => 'value1', 'key2' => 'value2');
would be exactly
the same as:
$arr = array(); $arr[] = 'key1' =>
'value1'; $arr[] = 'key2' => 'value2';
and print_r($arr)
would yield something like:
array ( [0] => whatever ['key1'
=> 'value1'] yields, [1] => whatever ['key2' => 'value2']
yields, );
That's because being => an operator, "op1
=> op2" is an expression and therefore it yields a value.
|
|
jlsalinas at NOSPAM dot gmx dot net
11-Jan-2003 05:14 |
|
It looks like a lot of people don't really understand what's an operator
(probably they come from the HTML field). An operator is something that
you feed with one or more values (or expressions in the programing jargon)
and yields another value (so that the construction itself becomes an
expression).
So you can think of functions or constructions that
return a value (like print) as operators and those that return nothing
(like echo) as any other thing.
This relates to the ternary
operator, ?:, as well. It should be used to select between two expressions
depending on a third one, not to select two sentences or paths of
execution. And always sorrounding ?: expressions with parenthesis is also
a very good idea. As I've had to program in a variety of languages, I've
got used to use parenthesis everywhere, and it's really worth it. They are
only two kesystrokes, but they can save you a lot of headaches.
I
hope this will be useful to those of you who have to dive into PHP without
a good programming ground. Don't desperate, it's really easy, and even a
joy! ;)
|
|
zontar at mindless dot com
12-Jan-2003 07:24 |
|
It would be really nice to see PHP support the logical
comparison-with-assignment operators &&= and ||=, e.g.
$a
&&= $b;
rather than having to write
$a = $a
&& $b;
It seems a shame to omit when these when we already
have support for +=, -=, &=, etc. Several other languages do so and
it's quite handy.
Just a thought.
|
|
fatz at fatkids dot com
22-Jan-2003 09:33 |
|
One caveat of this precedence is that: $variable = false or
true; will set $variable to false due to the fact that the or operation
is performed after the equals. For this type of situation you will want
to use $variable = (false or true); or $variable = false || true;
|
|
Bernard Blundell
27-Apr-2003 11:48 |
|
Don't get caught out by the syntactically correct (but usually wrong)
beginner's way of range testing:
if ($a <= $b <= $c) {
// OOPS }
The problem is that ($a <= $b) evaluates to 0 or 1,
then ((0 or 1) <= $c) is used to determine the whole
expression.
Obviously, you need to do this:
if ($a <= $b
&& $b <= $c) { // woo and yay }
|
|
wikiz at studentas dot lt
28-Apr-2003 09:25 |
|
Correct me if I'm wrong, but.. Documentation states that assignment has
lower precedence than, for example, sum (+) operator. but this example
shows that assignments go BEFORE the sum:
$a = 10 + $b=10; echo
"a=$a, b=$b";
outputs: a=20, b=10
I guess, php
is evaluating everything in this sequence: a =
(10+($b=10));
though by precedence table this should be:
a =
((10+$b) = 10);
..so it means that assignment has higher precedence
against sum operator.
|
|
jsorrell at ubiqinc dot com
14-May-2003 10:48 |
|
Regarding the note by wikiz at studentas dot lt
I think PHP is doing
a little sanity checking for you in the particular case you have
presented. The expression 10 + $b is not a valid lvalue, that is you
CAN'T make the assignment:
(10 + $b) = 5
That's like trying
the following assignment:
2 = 5
Since 10 + $b is an
expression, it evaluates to a single returned value, in this case whatever
the sum of the variable $b and 10 is. So, rather than throw an error
(which might be more appropriate) PHP is doing the assignment first, since
that is the only valid interpretation of the statement.
|
|
add a note |