Archive for the ‘PHP5’ Category

You Can Use If, Instead Of count()

Posted: June 28, 2010 in PHP5, PHP5.3

If your using arrays as a collection for a container of data, very few know that count isn’t always needed to know if an array has values or not. Here is a comparison:

$array = array();

// without count,
// shall output nothing.

// with count,
// shall output nothing
if(count($array) > 0)

Both work 😉


Why use Smarty? why use Twig? why use TinyButStrong? PHP is a ‘Template Engine’?

We use it to ‘separate PHP from HTML‘, .. or was it to ‘separate business logic and presentation logic‘ .. or .. was it because ‘I’m lazy‘ .. or maybe .. just maybe .. I’m using it because ‘everyone else is using it’.

It doesn’t matter which one you use or for which reasons you use it, as long as you understand the logic of why you use a template engine.


You can read all about this approach here: ObjectivePHP

When some method or function call can be specified with alternate options using a one dimensional array, for example:

function whoAmI($iam, $baboon, array('setme' => false, 'else' => true));

A lot of programmers tend to manually check the passed option keys and set it’s value, this is what
I see in a lot of tutorials on many PHP sites:

// function or method
function whoAmI($iam, $baboon, array $options = array()) {
  if(count($options) > 0) {
    $options['setme'] = empty($options['setme']) ? 'some_default' : $options['setme'];
    // rest of the key options ..

  // rest of function or method code

Then some programmers comment and say:

The empty is not the correct function to use on set keys. If the value of the key is false, then the return value of empty will also be false, although it should be true. A better solution would be to use the array_key_exists function.

$options[‘setme’] = array_key_exists(‘setme’, $options) ? ‘some_default’ : $options[‘setme’];
// rest of the key options ..

Although the problem with empty on array key/values is correct, the solution is far from better.