PHP Programming 101

December 10th, 2010

Array_diff_uassoc Function

Posted by Conrad in Basic Programming, Sample Code

Next in line is array_diff_uassoc() function which compares two or more arrays while checking for differences before comparing the keys with a user-defined location. It then returns an array withthe keys and values from the first array(to which all the values were comapred against) it the function allows it. Syntax is as follows : array_diff_uassoc(array1,array2,array3….,function). with a sample below of how it is used.

function userdefined($v1,$v2)
{
if ($v1 === $v2)
{
return 0;
}
if ($v1 > $v2)
{
return 1;
}
else
{
return -1;
}
}
$a1=array(0=>”Dog”,1=>”Cat”,2=>”Horse”)
$a2=array(3=>”Dog”,1=>”Cat”,5=>”Horse”)
print_r(array_diff_uassoc($a1,$a2,”userdefined”));
?>

which results in the following output : Array( [0] => Dog [2] => Horse). For an example of the same function with two or more assigned arrays to the function:

function userdefined($v1,$v2)
{
if ($v1 === $v2)
{
return 0;
}
if ($v1 > $v2)
{
return 1;
}
else
{
return -1;
}
}
$a1=array(0=>”Dog”,1=>”Cat”,2=>”Horse”)
$a2=array(3=>”Dog”,1=>”Cat”,5=>”Horse”)
$a3=array(6=>”Onyx”,0=>”Dog”,5=>”Horse”)
print_r(array_diff_uassoc($a1,$a2,$a3,”userdefined”));
?>

Which in turn, gives you : Array ([2] => Horse )

So we see the different array_diff function variants and the diffeerent ways they are used to compare the values of one or more arrays with one another.

September 10th, 2010

Random Numbers

Posted by Conrad in Basic Programming, PHP, Programming


int rand ( [int min, int max])
int mt_rand ( [int min, int max])
int getrandmax ( )
int mt_getrandmax ( )
void srand ( [int seed])
void mt_srand ( [int seed])

Sometimes you want to take random actions in your code – it might be to give your web site visitors a different greeting each time they visit, you might be programming a game, or you might be trying to secure data by hashing it. Either way, randomisation is simple and helpful thing to remember, and has just two functions: rand(), and mt_rand().

Both functions do the same thing, and both take the same parameters, so what is the difference between the two? Well, rand() is a basic randomisation function that is very quick but not very “random” – the numbers it generates are slightly more predictable. Mt_rand() on the other hand, is more complicated – the “mt” parts means Mersenne Twister, as that is the name of the randomisation algorithm it uses. Mt_rand() returns much more “random” numbers, but does so at the expense of some speed.

As mentioned, both functions have the same parameters – two optional numbers, for the minimum number to return and the maximum number to return. Either you supply no parameters, which will result in PHP returning a random number between one and a very high number, or you can supply the two parameters. Here is an example:

$random = rand();
$randrange = rand(1,10);
$mtrandrange = mt_rand(1,100);
?>

Note that the two numbers passed in are inclusive. That is, our $randrange number could be anywhere between 1 and 10 including 1 and 10.

As mentioned, if you do not pass any parameters to your rand() and mt_rand() calls, PHP will generate a random number from 1 to a high number. If you want to find out the maximum number PHP can return from a rand() call, use getrandmax(). There is a similar function, mt_getrandmax() for mt_rand().

Now you know how randomisation works, here is a quick example to show you how you can make use of randomisation to greet web site visitors in various ways:


switch(rand(1,6)) {
case 1:
$greet = 'Hello!'; break;
case 2:
$greet = 'Welcome!'; break;
case 3:
$greet = 'Greetings!'; break;
case 4:
$greet = 'Salutations!'; break;
case 5:
$greet = 'Good day!'; break;
case 6:
$greet = 'Yo!'; break;
}

print $greet;
?>

Here we have not bothered assigning the result of rand() to a variable before putting it into the switch statement, but you can do it whichever way is easier for you to read.

One important thing to note is that the speed of randomisation does not depend on the sizes you pass into it – rand() is just as fast in rand(1,3) as it is in rand(1, 10000000). Mt_rand() works just short of 50% slower than rand(), which means you should only be using it if you particularly need the extra randomisation it brings.

To give you an idea of how fast the two run and how using larger values for randomisation makes no difference, try this script:


$START = time();
for ($i = 1; $i < 1000000; ++$i) {
$j = rand(1,100);
}
$END = time() - $START;
print "Short rand() took $END seconds\n";

$START = time();
for ($i = 1; $i < 1000000; ++$i) {
$j = mt_rand(1,100);
}
$END = time() - $START;
print "Short mt_rand() took $END seconds\n";

$START = time();
for ($i = 1; $i < 1000000; ++$i) {
$j = rand(1,10000000);
}
$END = time() - $START;
print "Long rand() took $END seconds\n";

$START = time();
for ($i = 1; $i < 1000000; ++$i) {
$j = mt_rand(1,10000000);
}
$END = time() - $START;
print "Long mt_rand() took $END seconds\n";
?>

Most random number generators require “seeding” – initialising with a starting value – because the numbers they generate are not truly random. Instead, they are known as pseudo-random, meaning that they appear to be random. The seed value is used to generate the first number, the first number is used to generate the second number, the second for the third, etc, meaning that if you always supply the same seed value you will always get the same string of “random” numbers. This is actually advantageous. Many years ago there was a popular game called Elite available on the BBC Micro, where the player was allowed to fly around a large universe of eight galaxies, each with thousands of star systems. Each star system had a very precise number of planets, a distinct economy situation, etc, and yet the entire universe fit into just 22K of memory. How was this possible? Simple: by providing the same seed to their random number generator, the exact same universe could be generated each time.

Of course, this is a fairly rare situation. More often than not you will want numbers that look random as opposed to numbers that are always the same, and this is where random seeding comes in. If you provide a random number to the random number generator as its seed, you will have a new and original string of random numbers coming out. Does this sound like a chicken and egg situation to you? That is, how do we get the random number to provide to the random number generator? Well, think of what randomness – usually called entropy – you can draw upon in your scripts.

  • The number of files in your temp directory?
  • The number of rows in your database?
  • The time your script was called?

Of all three of these, the latter is potentially the most random – you do not control when your script is called, and you are certainly never likely to have the same script called in the exact same microsecond, so you could use the return value from microtime() as your initial random seed.

The seed function for rand() is srand(), and it takes one parameter – an integer to use as the seed value. If you are using mt_rand(), you should use mt_srand() for seeding. If you recall from earlier, microtime() returns a floating-point number – this is no good for use as the parameter to srand() (or mt_srand() – it is exactly the same), so you need to make it into an integer before use.

Now, as we know that microtime() returns the time in millionths of a second, we can convert its return value to an integer by multiplying it by a million, like this:

srand((double)microtime()*1000000);

The code above should seed the standard random number generator fairly well. You can do the same for the Mersenne Twister generator with this code:

mt_srand((double)microtime()*1000000 );

If you want your random number to always generate the same string of numbers, simply supply a seed that is a known value. For example, no matter how often you run it, this next script will always generate the same “random” numbers:


mt_srand(123456);
echo mt_rand(1, 100), "\n";
echo mt_rand(1, 100), "\n";
echo mt_rand(1, 100), "\n";
?>

The last option is just to call srand()/mt_srand() without any parameters at all. In this situation, PHP will attempt to generate a random seed for you – not much good if you want reliably random numbers or if you have a particularly good source of entropy for your seed value, but generally good enough for most people.

As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is done automatically.

Source

August 10th, 2010

Array Chunk Function

Posted by Conrad in Basic Programming, Sample Code

The array_chunk() function on the on the other hand as the name implies, divides an array into chunks or several tables from the source table. The syntax goes something like array_chunk(array,size,preserve_key), wherein the array is the table that would be divided, the size is the number of elements which the new arrays are to contain and the preserve key which can either be true or false is used to either retain or revise the key or pointer value of the original table. An example is shown below:

$a=array(�a�=>�Cat�, �b�=>�Dog�, �c�=>�Horse�,�d�=>�Cow�);
print_r(array_chunk($a,2);
?>

The code would have an output of:

Array (
[0] => Array ( [0] = > Cat [1] => Dog )
[1] => Array ( [0] => Horse [1] => Cow )
)

As we can see, the original array has been divided into two arrays array0 and array1 and a value that is not given for the key had it assigned a new key for each of the tables. Another example would be :

$a=array(�a�=>�Cat�, �b�=>�Dog�, �c�=>�Horse�,�d�=>�Cow�);
print_r(array_chunk($a,2,true);
?>

This would then give us ;
Array (
[0] => Array ( [a] = > Cat [b] => Dog )
[1] => Array ( [c] => Horse [d] => Cow )
)

This shows the significance of the retain key field wherein the two new arrays retained their original keys. The reverse of which would be the array_combine() which divided the array into one which holds the keys and one with the values.

July 10th, 2010

Reading the current time: time() and microtime()

Posted by Conrad in Basic Programming, PHP


int time ( )
mixed microtime ( [bool get_as_float])

PHP has a basic function to get the current time in epoch format: time(). Time() takes no parameters, and returns the current timestamp representing the current time. As time() is the first function we have looked at, here is an example script:


print time();
$foo = time();
print $foo;
?>

As you can see, we can either print the return value of time() directly, or we can store it away in a variable then print the contents of the variable – the result is identical.

Working in Unix time means you are not tied down to any specific formatting – you do not need to worry about whether your date has months before days or vice versa, whether long months are used, whether day numbers of day words (Saturday, Tuesday, etc) are used, and so on.

Furthermore, to add one to a day (that is, to get the date of tomorrow), you can just add one day’s worth of seconds to your current timestamp: 60 x 60 x 24 = 86400. So, adding or subtracting 86400 to a date moves forward by one day, and so on – easy, really.

For more precise time values, you can use the microtime() function. When called without any parameters, this returns the current system time in seconds and microseconds, ordered microseconds first. For example: 0.82112000 1174676574

If you pass true to microtime() as its only parameter, PHP will return the time in a more obvious format – seconds.microseconds, like this: 1174676587.5996

When using microtime(), keep in mind that the return value is a floating-point number. There is a setting in your php.ini file called “precision”, which sets the number of significant digits to show in floating-point numbers – note that is significant digits, not decimal places, which means your return value from microtime() may not be as precise as you want. Above, for example, you can see we only have four decimal places returned – this is because php.ini defaults precision to 14, and there are ten digits before the decimal place.

If you increase the value of precision up to, say, 18, and run microtime() again, you will get results that are more accurate: 1174677004.8997819.

Source

June 10th, 2010

Arrays : Changing cases

Posted by Conrad in Basic Programming, Sample Code

This form of array declaration allows one to change the case from uppercase to lowercase and vice versa. The syntax goes as follows:

array_change_key_case(array,case)

The array part, specifies which table or array to use and is a required field which is not the case with the key which is automatically assigned a value. An example of it’s use can be seen below:

$a=array('a'=>“Mouse”,’b'=>”Rat”,’c'=>”Rodent”,’d'=>”Cat”);
print_r(array_change_key_case($a,CASE_UPPER));
?>

The output of the said commands will be:
Array ( [A] => Mouse [B] => Rat [C] => Rodent [D] => Cat)

Another example of it’s use would be:

$a=array('a'=>“Mouse”,’B'=>”Rat”,’c'=>”Rodent”,’b'=>”Cat”);
print_r(array_change_key_case($a,CASE_UPPER));
?>

That returns the following values respectively:
Array ( [A] => Mouse [B] => Rat [C] => Rodent [D] => Cat)

In the next post, we would discuss an array function that divides a large array into several chunks of separate arrays.

May 10th, 2010

More Programming Basics

Posted by Conrad in Basic Programming

As with all programming languages PHP has different variable types such as numeric, character, string and Boolean types. Boolean variables in PHP always return either true or false, integers are whole numbers, floating points are decimal or scientifically notated and strings are a chain of characters. Sounds familiar, well they are and they are mostly standard across the various programming languages. For a more in-depth discussion on the different data types of PHP go visit the manual page.
We next discuss operators such as the assignment operator which allows you to assign values to variables allowing complex operations to be constructed into more and more functional programs.

April 10th, 2010

PHP and other Programming Languages

Posted by Conrad in Basic Programming

The major notable difference with PHP against other languages with regards to variables is that PHP is more “intelligent”. In C for example, variables have to be explicitly defined as either numeric or alpha-numeric and can only be used to store that defined specific form of data. PHP like all other languages supports a lot of variable types such as integers, floating point numbers, arrays and strings but with one major difference, variables are recognized automatically based on their use and the context of their use. This makes your (programmer’s) life a whole lot easier. PHP variables are defined with a “$” symbol preceding the variable name. It should also begin with either an underscore or an alpha character.

March 10th, 2010

Embedding Comments

Posted by Conrad in Basic Programming, Sample Code

Now, to make you a better programmer we all know the value of comments. This allows you to understand the code that you have written defining and given meaning to operations as you build them up. You start with the terminators used by PHP and end with them as well. Single line comments look like this �// comment� and Multi-line ones use the syntax /* comment comment*/. A better example would be the one below:

//comment
/* comment
Comment*/
?>

In the next post we take on the best parts of PHP which would be variables which is essential in all programming languages.

February 10th, 2010

More into the syntax of PHP

Posted by Conrad in Basic Programming, Sample Code

As you might have seen, all of the PHP statement ends with “;” which would be somewhat similar to Perl. The valid HTML code that was handed back to the server was :
Sample:
html>
head>
body>
Who are You?
br />
My name is MacGyver.
/body>
/html>
(Note: opening “<” were removed to allow display of the code)
More in the coming posts when we dig deeper as we widen our understanding of PHP.

January 10th, 2010

Dissecting/Understanding the first program

Posted by Conrad in Basic Programming

The first post had you making a program that was equivalent to the “Hello World” program used for teaching basics of a programming language and here’s how it worked. When the script was requested by opening the web page, Apache intercepted the request and passed it onto PHP which parsed the script looking for the code in between the terminators and then doing the requested operation which was to display the text contained within the echo command. This result was given back to the server then again to the client. The output contained a valid HTML so the browser was able to understand it and execute the requested operation.

Next Page »