PHP function for adding classes to html columns

When developing themes i’m always adding classes to grid columns, when this is output in WordPress or any CMS i have to check to see which column is currently being output and add the correct class to that column, For example using 960gs you have to use alpha and omega classes to remove the margins from the first and last columns. Well all you need to do now is add this helpful function to your theme and you can easily add classes to columns by taking the current record counter, and returning a list of classes which have been prevously set and that match the current counter.

<?php
/**
 * Generate column classes from the argument array
 *
 * Examples:
 * get_column_classes(1, array('first', 'last'), array('one', 'two', 'three'))
 * returns array('first', 'one');
 *
 * get_column_classes(3, array('first', 'last'), array('one', 'two', 'three'))
 * returns array('first', 'three');
 *
 * @param  int $counter
 * @param  array $classes
 * @return array
 */
function get_column_classes($counter){
 
    $output = array();
    $args = func_num_args();
 
    for($i = 1; $i < $args; $i++) {
 
        $classes = func_get_arg($i);
 
        $col = 0;
        $columns = count($classes);
 
        foreach($classes as $class){
            $col++;
 
            if($col == $columns)
                $check = 0;
            else
                $check = $col;
 
            if($counter % $columns == $check){
                if(is_array($class)){
                    $output = array_merge($output, $class);
                }else{
                    $output[] = $class;
                }
            }
        }
    }
 
    return array_filter($output);
}
?>

Now we need to add a function to say which class to be output for each column, this example will output classes for a three column layout (you can change the classes to be anything you want)

function the_column_classes($counter, $echo = true){
 
    $classes = get_column_classes($counter,
        array(
            array('one', 'first'),
            'two',
            array('three', 'last')
        ),
        array(
            'mob-first',
            'mob-last'
        )
    );
 
 
    $result = implode(' ', $classes);
 
    if($echo)
        echo $result;
    else
        return $result;
}
 
 
for($i=1; $i <= 6; $i++){
    echo "<div class=\"".the_column_classes($i, false)."\">RECORD: $i</div>\n";
}

The Above code should output the following:

<div class="one first mob-first">
  RECORD: 1
</div>
<div class="two mob-last">
  RECORD: 2
</div>
<div class="three last mob-first">
  RECORD: 3
</div>
<div class="one first mob-last">
  RECORD: 4
</div>
<div class="two mob-first">
  RECORD: 5
</div>
<div class="three last mob-last">
  RECORD: 6
</div>


Liked this article? help spread the word.