PHP Programmer – strlen, count and substr

November 24th, 2009

PHP Developer – strlen, count, and substr

The strlen function retuns the length, i.e. number of characters in a string:  int strlen(string s)

count will get the number of elements in an array:  int count(array a)

substr will return a “subset” of a string, string substr(string s, int start, [int len]);
<?php
$s = “test string”;
echo “String length is: ” . strlen($s);
?>

Will return:  String length is: 11

Why would you care how long a string is? Well, for many reasons, one being that you might wish to iterate through each character of a string to perform a certain conditional check or operation on each character. Alternatively, you might want to check that a certain string is not over a given size, and if so, shorten it. Here’s a common example that shows these three common functions together:

<?php
$myarray = Array("This is a very long string", "short string", "some text", "some more text to be shortened");
define(MAXLEN, 20); //maximum permitted string length
$num = count($myarray); //Get the number of elements in the array
for ($ctr = 0; $ctr < $num; $ctr++)
{
    if (strlen($myarray[$ctr]) > MAXLEN)
    {
        echo substr($myarray[$ctr], 0, (MAXLEN - 3)) . "...n";
    } else {
        echo $myarray[$ctr] . "n";
    }
}
?>

The above will output:
This is a very lo…
short string
some text
some more text to…

This could be used in an instance where we only want to show a predefined “taster”, i.e. replacing … with “(more)” or similar. Alternatively, ensuring that text does not overflow a “<div>” element in a particular instance

PHP Programmer – strpos, finding the position of a word in a string

November 20th, 2009

In PHP, we can use strpos to find the position of a character or string within another string:

int strpos  ( string $haystack  , mixed $needle  [, int $offset = 0  ] )

For example:

<?php
$mystr = “this is a test string”;
$pos = strpos($mystr, “test”);
echo “Position: ” . $pos;
?>

Returns:  Position: 10

We can just as easily use strpos to test for whether or not a given string is found in a larger string:

if (strpos($mystr, “test”))
{ … }

However, that may in some cases unexpectedly fail:

if (strpos($mystr, “this”))
{ … }

This will return 0, as “this” is at the beginning of the string and therefore at position 0, causing the condition to fail. The correct usage is:

if (strpos($mystr, “this”) === false) { … } OR  if (strpos($mystr, “this”) !== false) { … } noting the usage of “===” or “!==” meaning an absolute evaluation. As of PHP 4, “==” means “equal to” and “===” means “identical to”.

PHP Developer – Serialize

November 18th, 2009

PHP has two ver useful functions, serialize and unserialize.

serialize() generates a string based storable representation of any variable type that you like. Take a complex variable:
Read the rest of this entry »

PHP Developer – Loops in General

November 15th, 2009

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.
Read the rest of this entry »

Freelance PHP Programmer – Managing Estimates

November 10th, 2009

Dealing on larger projects and mediating between my PHP development team and the Client is often a far simpler task than acting as a sole freelancer. Having a very good and reliable team of 12 long term offshore PHP programmers, means that I now have sufficient confidence that I could theoretically just pass their overall estimates straight on to the Client without issue. Even still, I add at least 10% to the PHP developer’s estimates as well as subtracting at least 10% from the Client’s final delivery date. If we’re all happy and can agree on those deadlines, great. This allows for a comfort period for us, as well as the ability to iron out bugs and perform good QA on anything delivered.
Read the rest of this entry »

String replacement with sed

November 6th, 2009

Sed – stream editor is a powerful tool to manipulate strings. It will take STDIN as well as operating on a file:

The most common usage is to replace text:  echo “this is a test string” | sed s/i/z/g will replace every instance of ‘i’ with a ‘z’:  thzs zs a test strzng

You can delete a particular word with say echo “this is a test string”| sed s/test//g leaving: this is a  string

You can operate on a file with:

echo “this is a test string” >> file; sed -e s/test//g file Leaving: this is a  string

You can also use regular expressions with sed.

PHP Developer – Looping through database results

November 5th, 2009

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..

Easy Reverse Engineering

November 2nd, 2009

Compiling a program doesn’t protect it or necessarily hide the source. Take the following example C program. It serves no real life purpose and should never print anything to the console:

#include <stdio.h>

int main(void)
{
        const char *password = "secretpassword";
        const char *otherpassword = "othersecretpassword";

        if(!strcmp(password, otherpassword))
        {
                printf("This will never get evaluated");
        }
        return 0;
}

To assemble the code using gcc -S test.c leaves test.s. The important point being that all strings remain intact:
Read the rest of this entry »