php best practise

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I am a php newbie although I have been a programmer for years, this can be
dangerous because all the languages I know use = as equal comparison so it
took me a long time to debug  if ($STRING = 'fred') { not realising I was
assigning fred to $STRING and the evaluation is always true! It took ages to
discover if ($STRING = = 'fred') {.

I eventually managed to create a validated form which re-displays with an
error list, but I have a few questions about 'best practise' programming
because my solutions seem a little clumsy:

Combobox selection: How do you set a default or remember what the user
selected so the form is re-displayed with their selection. I did this: Item1
= '< -- Select a Country --> as "selected", I then changed the text to the
actual selection using echo if the form is re-displayed, Question: How do
you dynamically set a default or dynamically move the SELECTED tag?

<option selected><?echo $COUNTRY?></option>

Radio Buttons: I assigned each with a <? echoDEFAULT1 ?>, <? echo DEFAULT2
?> etc and set each to "" except for the default I really want, this is set
to "checked", surely I am not doing this the right way?

<input type="radio" value="MSWORD" <?echo $CKWORD?> name="RB1"
tabindex="14">Microsoft Word<br>
<input type="radio" value="TXT" <?echo $CKTXT?> name="RB1"
tabindex="15">Text File<br>
<input type="radio" value="PDF" <?echo $CKPDF?> name="RB1"
tabindex="16">Portable Document Format (PDF)</td>



Re: php best practise


For a combo box (drop-down select), use something like this:

<label for='fld_location' accesskey='L'><u>L</u>ocations:</label>
<select id='fld_location' name='location[]'>
 $locations = pg_query($db_conn, 'SELECT name FROM locations ORDER BY
 if ($locations) {
  while ($location = pg_fetch_object($locations)) {
   echo '<option

The ternary operator (cond?val1:val2) is used to check each option. If
the option is the one currently selected output selected='selected',
otherwise output an empty string. If you have a static list (as opposed
to a database query), just put the ternary operator in each of the
options checking each options value against the current selection.

So the same thing in radio buttons using the ternary operator except
use checked='checked'. Hope that helped.


Re: php best practise

Best practice would be to use a class that encapsulates all of this,
where the basic logic would be, more or less, in a simple model:
Have a value that keeps the track of the selected item, an array of all
the items, and a loop that checks if the currently outputted value is
selected or not.

in almost-correct-code:

$options = array();
$options['msword'] = 'MS Word';
$options['txt'] = 'Text File';
$selectedKey = null;

echo "<selct bla bla>";
foreach($options as $key=>$value) {
    $selected = '';
    if($key == $selectedKey)
        $selected = 'selected';
    echo "<option name='foo' value='$key' $selected>$value</option>"
echo "</select>"

You can use the same procedure for radio buttons.

Re: php best practise

Here's one way you can do that - have a function similar to this:

function selectValue($name,$value) {
   if(isset($_POST[$name]) && $_POST[$name] == $value) {
     return ' selected="selected"';
   } else {
     return '';

Then, in your option list, do this:

<select name="myOption">
   <option<?=selectValue('myOption','Option A');?>>Option A</option>
   <option<?=selectValue('myOption','Option B');?>>Option B</option>


Barry Morris wrote:
Quoted text here. Click to load it

Re: php best practise

I do something similiar. For added flexibility, I pass the field value
instead of the index into $_POST. I also have the function perform the

Here's the equivalent for checkboxes and radio buttons:

function checked($current_value, $item_value) {
    if(is_array($current_value)) {
       $checked = in_array($item_value, $current_value);
   else {
      $checked = ($current_value == $item_value);
   if($checked) {
     echo "checked";

<input type="checkbox" <? checked($ck, 'hello') ?> name="ck[]"

Re: php best practise

I've been programming since the middle of the 20th century and I still
type '=' when I mean '=='. One trick I learned is this:

if ($string = 'fred') will NOT generate a syntax error.

if ('fred' = $string) WILL generate a syntax error. You can't assign a
variable to a constant.

Put the constants first in compares and if it's not '==' it will warn

That doesn't solve you larger problem, but it might help avoid one
common debugging annoyance.

--gary shannon

Re: php best practise

Thanks for that tip, I had a similar problem with syntax once before, I  
could not for the life of me work out why the Wang interpreter was throwing  
an error when I tried to display text in the middle of the screen. I had  
only just come from programming ICL VME computers (British) so no matter how  
hard I looked I could not see that CENTRE was spelt wrong. Good job the Wang  
was not in colour!


Re: php best practise


One thing about that is that it is counter-intuitive to read. For
example you are not asking "if 'fred' equals your name..." but rather
"if your name equals fred'...".

That said, your method is a very practical solution to a common

In a way I kinda wish that the '=' operator worked like the ECHO
construct in that you wouldn't be able to use it as a function. That
way if your source tried to actually look at the result of an '='
assignment a syntax error would occur (like the distinction between
echo and print). The only side effect would be that you would be unable
to chain assignments like this:

a = b = c = d = 0;

But an alternate method could be added to the language such as:

(a, b, c, d) = 0;

Which I think is actually used by LISP if I recall correctly.

But of course I'm just dreaming/thinking out loud here. :o)


Re: php best practise

rlee0001 wrote:
Quoted text here. Click to load it

Why not change all the primitives to objects and then move the '='  
operation to equal()? Then you could have:

Or DEFINE the '=' to be '.equals.'? Then it would be:
$a .equals. $b

[Just joking. Programmers in other languages may recognize these.]


Re: php best practise

Thanks for the tips and example code. Are there any php books you can  


Re: php best practise

Are you using PHP 4 or 5?

I thought PHP and MySQL Web Development by Luke Welling and Laura  
Thompson was a good book for learning PHP 4.  I don't know if they have  
a new edition out for PHP 5 yet.  Make sure you don't get the 1st  
edition of that book, though, because it was written before some of the  
major changes to PHP 4 were out, such as register_globals disabled by  


Barry Morris wrote:
Quoted text here. Click to load it

Site Timeline