$nameclass=$companyclass=$address1class = "text"; if (in_array('name', $values)) { $nameclass = "error"; } if (in_array('company', $values)) { $companyclass = "error"; } if (in_array('address1', $values)) { $address1class = "error"; } <input class="'.$nameclass.'" type="text" name="name" size="25"/> <input class="'.$companyclass.'" type="text" name="company" size="25"/> <input class="'.$address1class.'" type="text" name="address1" size="25"/> Code (markup): Can it be simplfied at all, perhaps using a FOREACH loop or a SWITCH statement? Not sure if it will help matters but the $xxxxxxclass in each IF statement begins with the name of the attribute in the array.
Of course. $attributes = array( 'name', 'company', 'address1' ); foreach ( $attributes as $value ) echo '<input class="' , (in_array( $value, $values ) ? 'error' : 'text') , '" type="text" name="' , $value , 'class" size="25"/>' , "<br />\n" ; PHP:
Cheers for that mate. Can you explain how this bit works: ? 'error' : 'text' I've seen that syntax in a few places but never quite understood it.
Ternary operators, if the boolean expression before the ? equates to true, then it runs the code between the ? and :, otherwise it runs the code between : and ; I.e. echo (if this == true) ? 'if it returns a boolean true or equivalent' : 'if it does not.'; Notice it is only ==, not ===. Type is not relevant here. Here's more information: http://uk2.php.net/operators.comparison#language.operators.comparison.ternary
Thanks for clarifying that. I've just realised I might fall in to a small problem when using the foreach loop. Basically all my fields are prefixed with their label, such as: <b>Contact Name:</b> <b>Company Name:</b> <b>Address Line 1:</b> Do I need to put these values in an array too, if so how?
$attributes = array( 'name' => 'Name', 'company' => 'Company', 'address1' => 'Address Line 1' ); foreach ( $attributes as $key => $value ) echo '<b>' . $value . ':</b> <input class="', ( in_array($key, $values) ? 'error' : 'text' ), '" type="text" name="', $key, 'class" size="25"/>', "<br />\n"; PHP:
Hi Danltn The code works fine - thanks! Slight issue though - upon first load of the page I get the following error: in_array() [<a href='function.in-array'>function.in-array</a>]: Wrong datatype for second argument This doesn't get displayed on screen but it's there in the generated HTML source code. Do I need to use the isset function anywhere?
$attributes = array( 'name' => 'Name', 'company' => 'Company', 'address1' => 'Address Line 1' ); foreach ( $attributes as $key => $value ) echo '<b>' . $value . ':</b> <input class="', ( in_array($key, (is_array($values) ? $values : array())) ? 'error' : 'text' ), '" type="text" name="', $key, 'class" size="25"/>', "<br />\n"; PHP: