Archive for the ‘php’ Category

Change the css class of every second row with php

Tuesday, April 28th, 2009

If you need to find odd numbers in an array in php it’s very easy. You just use the “%” command. eg.

if ($num % 2) {
echo “$num is odd”;
} else {
echo “$num is even”;
}

I think what it basically does is divides the number by 2 and if it’s not a whole number it renders it returns it as odd.

Here’s how this code can be very tidy and useful:

The following code can be helpful if you are doing a php foreach repeater to produce a table and you want to use an alternating css class on every second row.

Step 1:
Place a $count outside your foreach loop.

$count=”0″;

Step 2:
Create your rows with the alternating css classes

echo “<tr class =’”;
$count++;
if ($count % 2) {
echo “rowclass1″; }
else {
echo “rowclass2″;
}
echo “‘>”;
echo “<td>Your row Content</td></tr>”;

That’s it, each row will have a different css class and it saves you having to do each row manually!

Table Rows ALternating

php drop down box list of countries made by foreach array

Sunday, April 19th, 2009

This is some code I wrote to generate a drop down box with all the countries listed in it,  that will preselect the right country if you post the country to it from a previous page. Really helpful if you use it as a control. I have it permanently in my PHP includes folder and just call it any time I need it.eg.:

 <select name=”example”>

<? include ‘../inc/countries.php’ ?>

</select>

Here is countries.php

(more…)

Round your values in PHP using Math Functions (using number_format)

Sunday, April 19th, 2009

To round any number or integer values in PHP it’s simple.number_format is useful function that you can use. It takes 2 values: the $NumberYouWantToFormat and then the number of decimal places you want it to be formatted to. 

$total = 34.128252 echo number_format($total, 2)

This will produce:

34.13 

It’s a simple thing, but really useful.