There are 3 types of loop in PHP:
while (condition)
{ code_goes_here; }
do
{ code_goes_here; }
while (condition);
for(expr1, expr2, expr3)
{ code_goes_here; }
In terms of the ‘for’ loop above, ‘expr1′ being the starting expression, i.e. $i=0. expr2 being the condition that must be satisfied to keep the loop running, i.e. $i < 100. expr3 being the expression evaluated each time the loop runs, i.e. $i++. Each loop type has it’s uses.
(more…)
Tags: do, for, loop, MySQL, PHP, PHP Developer, PHP MySQL Developer
As a PHP Programmer, a very routine PHP/MySQL procedure is fetching a set of records from the result of a query.
$sql = "SELECT ...";
$result_set = mysql_query($sql);
for ($ctr = 0; $ctr < mysql_numrows($result_set); $ctr++)
{
$my_object = mysql_fetch_object($result_set);
//do something with $my_object
}
Now as tidy as the above code is, what’s the big problem? The number of rows returned by the query remains the same throughout. Why are we calling the mysql_numrows function on the same result set, to return the same answer over and over, possibly thousands of millions of times depending on the size of the result set? On a larger web application with a larger result set, things like this will dramatically increase unnecessary overhead. This is one of the most basic optimizations to make:
$sql = "SELECT ...";
$result_set = mysql_query($sql);
$result_num = mysql_numrows($result_set);
for ($ctr = 0; $ctr < $result_num; $ctr++)
{
$my_object = mysql_fetch_object($result_set);
//do something with $my_object
}
Now, there’s a couple of different methods you can use to achieve the same purpose, some of which may actually be more appropriate, such as a simple while loop, but the purpose of this article was to illustrate the issue above solely. More on optimization later..
Tags: for, loop, MySQL, PHP, php programmer, sql
I was asked today how to sort a string alphabetically with BASH
Using perl, you can easily enough use
print (join “”, sort split //,$_)
With bash however, the best option is:
echo “teststring” | grep -o . | sort -n |tr -d ‘\n’; echo
Which returns: eginrssttt
A good way of enumerating each character from a string in general is:
for (( i = 0; i < ${#str[@]}; i++ )); do echo “${str[$i]}”; done
Tags: bash, do, done, echo, for, grep, perl, print, shell, shell scripting, sort, string, tr