PDA

View Full Version : PHP tips


Merlin
01-30-2010, 09:45 PM
I struggled with a bug, that I tracked down to a series of nested if/else statements. I had a block of code that gathered defenders.

My code initially looked like this:
if (($def['tactical_x'] == $dx)
&& ($def['tactical_y'] == $dy)
&& ($def['hits'] > 0))
if ($spell_use[0] == 'F')
if (in_array($def['player_id'], $allies)) { // <-- else associates with this if
$defender[] = $def;
}
else
if (! in_array($def['player_id'], $allies)) {
$defender[] = $def_unit;
}
In the original code, no grouping was required, but changes introduced a bug. In spite of my pretty indentation, the else associated with the last if instead of the $spell_use. Doh!

So, note to self: always include braces!
if (($def['tactical_x'] == $dx)
&& ($def['tactical_y'] == $dy)
&& ($def['hits'] > 0)) {
if ($spell_use[0] == 'F') {
if (in_array($def['player_id'], $allies)) {
$defender[] = $def;
}
} else {
if (! in_array($def['player_id'], $allies)) {
$defender[] = $def_unit;
}
}
}

Merlin
02-14-2010, 01:38 AM
One of the problems I've had with the DB class is that when you pass an array to a function, that often is passed as a copy of the array, so modifications to that array in the function don't get propagated to the original.

Use an ampersand (&) to create a reference to the original in the function arg list, so changes are made to the original array.
function modify_array(& $the_array, $copy_array) {
$the_array['item'] = $new_value; // <-- this will modify the array in the caller
$copy_array['item'] = $new_value; // <- this modifies only the local copy
}

Merlin
08-17-2010, 01:32 AM
There is a PHP option to allow a short tag "<?" instead of the longer "<?php", but for portability, use the longer tag, as support for the short tags varies by host and server.