Mcloide's resources library

All about PHP, Javascript, concepts and development

Posts Tagged ‘learn’

PHP Basics Series – Conditional Statements

Posted by mcloide on July 8, 2009

PHP Conditionals Statements are a true variation from C/C++ and they are, in fact, decision making structures. They are part of a set of control structures that is in fact your toolbox of PHP code.

For truly understanding how a conditional statement work, you have to get back to real hardware logical structures. When you study digital designs you learn that every processor, multiplex, works with a bunch of elements that, according is set on the circuit board, decisions will be made getting the correct result for you (click in the image).

When working with PHP conditional statements you will find most of those real elements that you find inside many electric hardware and they are as important as such. Just keep in mind, whenever you need to code a decision, you will need at least 1 conditional statement.

PHP’s conditional statements are:

[Note:] all PHP structures are lower case

Most likely, when working with a if statement, you will be also working with a else statement, but, in some cases, where you have a nested or sequenced structure with many if and else’s, your best choice will be the switch.

The if and else statement are pretty simple:

<?php
if ( expression )
{
// do what needs to be done
}
?>

If you got another situation that you also need to test, but is just one more situation, then you will use the else, following the if.

<?php
if ( expression )
{
// do what you need to do
}
else
{
// was not what you expected before, so do this now
}
?>

To better visualize the code, let’s take a real situation, for instance, parsing the information sent by posting a form.

<?php
$name = ”;
if ($_POST['login'] == ‘John’)
{
$name = $_POST['login'];
}
else
{
echo ‘Error: Unable to log into the system. Wrong username.’;
}
?>

Some times will be needed to handle more than one else statement, or more than one condition to test after the first condition (if). There are actually 2 ways to do that, sequence some else followed by a if, or better known as elseif, or use the switch. There is no real rule to when to use what, but here is a tip, if you have more than 1 elseif, then use a switch.

<?php
if (expression)
{
// do what you got do
}
else if (another condition)
{
// do another thing
}
else
{
// last condition
}
?>

The code can be written, also,  using a elseif, instead of a else if. No real difference between the both, so it will be more how the programmer likes to code. Anyway, as mentioned before, when you have a long sequence of elseif’s, in most of the cases, you will be able to replace them for a switch structure.

The switch statement will allow to compare a same variable with a bunch of different values and you can easily math one or more comparisons to the same action.

<?php
switch ($_POST['todaysDuties'])
{
case ‘take garbage out’: // consider the case as a if
$need = true;
break; // and always add a break, otherwise it will continue to the next statement

case ‘take dog to the vet’:
case ‘give dog a bath’: // here we are seeing 2 conditions set to the same action
$need = false;
break;

default: // this is the default statement, or better know as else
// do nothing
break;
}
?>

[Note:] If you need to do a comparison that have more than one condition such as if equals something, or bigger than something else, place the condition inside parenthesis. Just like a if statement, it will look if the condition is true or false, so the conditions need to be worked as math expressions so the result is always correct, or the expected result.

Looking at the figure (top of the article), it shows a logical diagram for a circuit in which will get the signal entries from x1 to xn, invert them (or saying NO to it), pass them into a AND array, going to a OR array and finally going to an XOR array that will result the final output. These elements, that will return some logical choices of true or false when combined, are also used on combined expressions of an conditional statement.

The most common operators that is used inside a conditional statement are:

  • == : double equals : equals to (a single equal is receiving some value)
  • === : triple equals : identical to (in every single way, from type to value)
  • || : double bars : or
  • && : double commercial e’s : and
  • ! : exclamation point : not
  • != : exclamation point followed by a equal : not equal to
  • >, <, >=, <= : numerical operators

For example porpoises only a if statement could be easily represented by:

<?php
if ( ((!expression) && (expression)) || (expression))
{
// do something
}
else
{
// do something else
}
?>

There is another way to declare if / else statements in a single line without using the if or else. This is the short version of the code and, even knowing that it’s easier to use it while declaring variables or echoing, keep in mind that many developers does not know or can easily read them.

A short version of an if / else is declared as:

<?php
$variable = (expression) ? ‘get this value’ : ‘get another value’;
// this can be read as the variable will receive ‘get this value’ if the expression is true, else, it will ‘get another value’
?>

The same can be done to be used while outputting something and it also can support in-line (nested) short statements (not recommended – harder to read).

As many others controllers and structures from PHP, the conditional statements can be nested in many levels and can also be included inside other control structures.

To better practice how the conditional statements work, look for questions that can be programmable and the result of the conditional expression can be set to true,  false or maybe (in this case, an elseif that will return true or false).

Have fun.

Posted in PHP, development | Tagged: , , , , , , , , , | Leave a Comment »

PHP Basics Series – Arrays

Posted by mcloide on July 6, 2009

When working with PHP Arrays are by far the most flexible structure that you can deal with. If we look back to C++ language and looked to the structures for controlling Stack, FIFO, Priority List, etc, we had to define the whole structures to work with.

PHP offer you object construction to help you creating that or Arrays (and SPL – will discuss this later, in the advanced series).

To have an idea how flexible arrays are, they are used from storing retrieved data information from the database to holding session variables.

When talking about arrays you can really write a book about it, but to give a focus on the context and make it simple, I will be showing how the structure works, a simple output function, some sorting functions, the list function and pointing up some functions that you must know.

The array structure is pretty much a system of KEY pointing to VALUE, where the value can be anything scalar (0 => ‘value’) or dynamic (0 => array()) and the key have to be a scalar value restricted to integer and string.

There are a couple of ways to declare an array, but the best and effective way is to declare it blank and then add the values.

$newArray = array();

There is no real performance or reason why you should not add the values on the array while declaring it, but it really does help the code to be cleaner and more readable.

Arrays can hold other arrays inside of it and this can go on and on, so, if you need to declare a multi-dimensional array, just place an array inside another. All the rest is only accessing it’s values.

3 level array

$multi = array();
$multi[] = array();
$multi[0][] = array();
$multi[0][0] = ‘the final value’;

As mentioned before the arrays can have 2 types of keys, integer and strings. These types of keys are precisely the ones that will split the array in 2 categories, common arrays and associative arrays.

The associative arrays are largely used while working with database and form processing. You can easily set the key to be the column name and it’s value the current row value. The common arrays is the default type, so every time you declare an array, unless you declare the key as something different, it will always be an integer. On the common array, unless specified, the array will always start at zero, but you can set it to place the value on a given key.

Just to give some examples, here are the 2 types:

$associativeArray = array();
$associativeArray['first_name'] = ‘John’;
$associativeArray['last_name'] = ‘Smith’;

// usually while working with database you would dynamically set the array in a for loop

$commonArray = array();
$commonArray[] = ‘John’; // or $commonArray[0] = ‘John’
$commonArray[] = ‘Smith’;

Accessing the array both arrays would be pretty direct. On the associative you would go by:

echo $associativeArray['first_name']; // will display John

and the common array you would use an integer starting at 0:

echo $commonArray[0]; // will display John

Off course the associative array is more meaningful while working with data and it’s also the array type used on the $_SESSION, $_POST, $_GET and $_REQUEST arrays. The session array keeps every single information about the current session (if the session is set and started), the one from PHP and the ones that you are storing, like, for instance, a user login encrypted information or even a shopping cart list.

Consider that you have a shopping cart application and you need to store the cart contents in the session array. The best way to store it is by keeping the array with the shopping cart list inside the session array.

$_SESSION['cart_list'] = $arrayOfShoppingCartList; // a pre-existing array with all the current user selected products and it’s quantity.

While programming, some times, gets hard to know what the array is storing, so outputting it is always a good way out to debug. The best way to output an array is by using the print_r function, while echoing will only display “array” as result.

While debugging use:

<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>

It would result:

Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)

Outputting the array contents for the user needs some more attention. You can use the array_walk function and associate a function with it to display the array elements or you can simply add a loop to go trough the array and print it’s content.

To finish up let’s just take a look on a couple of array sorting functions and a great function, list:

  • asort – will sort an array and keep the index association
  • sort – will sort an array, from lower to higher, but reogarnizing the indexes
  • ksort – will sort an array by key

The list function is a great tool to dinamically attach an variable to each element from an array, associative or not.

list(‘fname’, ‘lname’, ‘zip’, ‘country’) = array(‘John’, ‘Smith’, 33065, ‘USA’);

The list function will dinamically create the variables $fname, $lname, $zip and $country with the array values (in sequence). The only thing to be careful about is that list requires that the number of variables created is also the number of values of the array.

list(‘fname’, ‘lname’, ‘zip’, ‘country’) = array(‘John’, ‘Smith’, 33065); // will throw an error

There are 3 functions, not mentioned at this article, that you should take a look at on the PHP documentation:

  • explode and implode, the only 2 php functions which will allow you to convert an string into an array and vice-versa (Zend Exam)
  • is_array is a great tool on if statements that will allow you to easily verify it the value passed is really an array

Check the PHP documentation for all arrays functions. Most of them got examples and get confortable working with arrays. They are the by far the structure that is most used on any PHP script.

http://us2.php.net/manual/en/ref.array.php

On the advanced series, I will be focusing a bit on the SPL structure. It came with PHP 5.3 and will probably be a nice substitute for the array. The benchmarks, so far, are poiting for it being faster, way faster.

On the next article we will be having an overview of the conditional structures of PHP.

Have fun.

http://search.scottslawnservice.com/index.cfm/event/about_whatToExpect

Posted in PHP, development | Tagged: , , , , , | Leave a Comment »

PHP Basics series – Coding

Posted by mcloide on June 29, 2009

code-standardThis is the first article that I’m writing about learning PHP.

For a couple of months now, and even more after this article from Marco Tabini, I have noticed the need of  better coding standards and a more directed learning content for “greenhorn” programmers in PHP.

Based on this, I’m starting today with a PHP Basis Series that will try to get around all the basic need that a developer should have to program well in PHP.

This first article will cover everything you need to know about coding and it’s standards.

You can learn PHP, Javascript, Java, C#, ASP.Net, Ruby on Rails, etc, if you don’t have good programming techniques and standards, your code will be messy, unreadable, hard to understand, etc.

It’s important that you have good standards and coding techniques and to emphasize that I quote a professor of mine that once said: ” A good developer learn the best pratices, standards and coding techinques, so he can program in any language.”.

While talking in PHP we have a small list of good coding practices / standars and methods.

When declaring variables and functions, use camelCase.

It’s actually simple. The variable or function will have it’s name started with a lower case and the next word will have the first letter uppercase and this will repeat for every word after.

Constants are always UPPERCASE.

This rule is more to help you out on identifying the constants among the variables.

Variables, functions names and constants must have a meaningful name.

Consider the following function:

function funtion_1($var, $var2)
{
for($i = 0; $i < $var2; $i++)
{
$var = $i + $var2;
}
return $var;
}

Looking it like this, it’s very, very hard to understand what is the use for the function or what each variable means, but re-writing it like this:

function increaseByMany($numberSource, $counter)
{
for($index = 0; $index < $counter; $index++)
{
$numberSource = $index + $counter;
}
return $numberSource;
}

It get’s really easier to understand whtat is doing and what it will return.

Use 4 spaces instead of Tabs.

Consider that you are working remotely with other developers from all over US and the World. Each developer has it’s own preferable editor. The only problem with this is that each editor can be configured to set the number of spaces for the tabs, so a developer can have 8 spaces instead of 4, for each tab. With the objective to have the correct indentation on every editor, instead of using tabs, use 4 spaces. It will be annoying at first, but it does really pay in the long run.

Have the minimal documentation for the system even if it is on the function / class itself.

This example is better visualized on a object class. Consider the creation of a class that handles every single action that a user can do on the system and this class was created more than 6 months ago. If you don’t have any inline documentation, or any documentation at all, understanding the methods inside and some specific methods from the class can be very hard. To avoid that and to allow other developers to understand how the class works, you should at least do inline commeting.

Some systems like PHPDoc, can grab the inline comments that you have written on your class and convert it, automatically, to a very professional system documentation.

Consider working with Object Oriented Programming, scalability and modularity.

Even if you are starting, working with Object Oriented Programming is a need and doing it so in a modular and scalable way is a must. The reason to work with OOP is simple: code re-use and modularity. If is well developed, you can easily allow a developer to work on a part of the system while you work on another, or you can let a developer to use a object that you already have created on his part of the system. The most important thing is that the system get’s easier to read, easier to maintain and you win on development time since you wont need to re-invent the wheel. The scalability is something that every system should consider on it’s beginning. If your system is not scalable enought there is a good chance that at some point, it will fail because it can’t grow.

Do your analysis before witting anything.

In one of my first jobs I have worked as a system architech and it was insane hard to convice the CEO that before acting, we need a plan, or by that I mean, we need to do analysis. Every time that my team tried to create something without discussing it first, things did go wrong, so, from a personal experience, if you are the system architech, do your analysis on the issue first. It will save time and you will be albe to consider how modular and scalable it can be.

Specifically to PHP

1. Never use short tags and it’s variations
2. If the document only contains PHP code, no need to use the PHP close tag ( ?> )

These are the very few basics from coding pratices / standards. Before writting a code always consider that it can become huge, that it can have 10 milhon users at time and, most important, that another developer will be reading it.

This will help you to write better code and as an advise, get the best coding standards that are out there, make a list and set on a document so every system that you work from now on you can use those and, off course, if someone joins the boat, you can send him that document too.

Have fun.

Posted in PHP, development | Tagged: , , , , , , , | 4 Comments »

Babel

Posted by mcloide on November 6, 2008

I was reading a article from the Crunch Network about a new social network site where you can learn new languages – Babbel.com.  Ok, I’m talking that they are teaching new programming languages, but, as speaking and reading more than one language besides your own is something always usefull (imagine yourself trying to take a subway in Japan) and I must admit, I was impressed with the site.

A great web 2.0 interface, the lessons have voice attached to (which make’s easier to understand) and after you start, you can spend a great amout of time there just checking the features of it.

I havent checked everything from the site still, but I have found some small bugs, that, at least for me, didn’t affect as much.

If you are the kind that like to learn something new everyday, check this out, you might stay there for a while.

Posted in Uncategorized | Tagged: , , , , | 1 Comment »