• Welcome to Tux Reports: Where Penguins Fly. We hope you find the topics varied, interesting, and worthy of your time. Please become a member and join in the discussions.

Using an Array

Dashboard Support Widget Array.png


A PHP array is a great way to group items together into one variable then loop through to retrieve the information. Arrays are an important tool in PHP development. A tool I've stayed away from writing in my code until recently.

Let me explain.

The other day I was looking at the dashboard support widget. It was written almost 4 years ago and only touched, and never rewritten. The widget relies on lines and lines of echo statements. The widget works but the coding is embarrassing.

I started to rewrite the widget to place the information into an array. The greatest challenge is not being able to add a conditional inside the array. Instead, I have to have extra arrays and use a conditional to determine which array to pull.

PHP arrays are very easy to create. The variable name is set equal to an array() and information is placed within the parentheses. Each piece of information is separated by a comma.

The information is retrieved through a foreach loop. One line is replacing dozens. It's gorgeous.

PHP:
foreach ( $info as $key => $value ) {
   echo '<tr><td style="width:40%"><strong>' . $key . ' : </strong></td><td style="width:60%; float:right;">' . $value . '</td></tr>';
}

Blog entry information

Author
LPH
Views
1,773
Last update

More entries in Technology

More entries from LPH

Top