A really wacky design decision

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Daevid Vincent is surprised that:

$num = 123;
$num = $num++;
print $num;  //this prints 123 and not 124 ?!!

To me this is relatively logical. As I understand it, the post-increment operator says "do
something with the variable, and then increment it. The trouble in this case is that we
are doing something irrational; we are copying the number back to itself, and to me it is
reasonably logical (or at least no less illogical than the alternative) to assume that if
we copy it to itself, then increment the original version, the copy will not be
incremented. 

However there is one feature of PHP which, to my mind, is really bad design. How many of
you can see anything wrong with the following procedure to search a list of names for a
particular name?

$i = 0; $j = count ($names); while ($i < $j)
	{ if ($names[$i] == $target) { break; }
	++$i;
	}

As long as the names are conventional names, this procedure is probably safe to use.
However if you allow the names to be general alphanumeric strings, it is not reliable. One
of my programs recently broke down in one particular case, and when I eventually isolated
the bug I discovered that it was matching '2260' to '226E1'. (The logic of this is: 226E1
= 226*10^1 = 2260).

I agree that I was well aware of this trap, and that I should not have used a simple
comparison, but it seems to me to be a bizarre design decision to assume that anything
which can be converted to an integer, using any of the available notations, is in fact an
integer, rather than making the default to simply treat it as a string. It is also a trap
that it is very easy to fall into if you start off thinking about simple names, and then
extend (or borrow) the procedure to use more general strings.

And can anyone tell me whether, in the above case, it is sufficient to write simply: 
    if ((string) $names[$i] == $target), 

or should I write: 
    if ((string) $names[$i] == (string) $target)? 

(I decided to play safe and use strcmp ().)


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux