Get up to 80 % extra points for free! More info:

The most common programming mistakes 2

You'll learn how conditions are evaluated, you'll find out the difference between a NULL value in a programming language and SQL, you'll learn two ways to convert a variable's type, you won't make a mistake when printing an array element and you may shorten part of your source code. :-)

Condition evaluation

To get started, it's important to know what is an expression and what is a statement. For example, an expression can be a mathematical operation. It can always be evaluated whether it's true or false. For example, a simple expression can be a sum of two variables:

$a + $b

If we want to find out an expression's truth value, we can primarily use constructs with some condition (if, elseif, while, switch, etc.).

In contrast, a command is something to be executed. For example, 'store this value in a variable'. There is a semicolon at the end of each command. Some beginners in a programming language confuse these two terms and sometimes forget a semicolon or put it at the wrong place. $result = $a + $b is an expression, while $result = $a + $b; is a command.

Expressions are always entered in conditions (if you tried to pass a command, it'd throw an error). It's always evaluated whether an entered expression is true. In other words, whether an expression equals TRUE.

This means that instead of:

if ($expression == true)

just write only:

if ($expression)

Some beginner programmers aren't very aware of this, but for example they know that in negation they can only write:

if (!$expression)

instead of including == true. This is the same case.

However, another case is when we want to test not only an expression's value, but also its data type. Conditions automatically convert an expression's data type to a truth value (TRUE / FALSE). This means that if we pass a string to a condition, for example, it'll convert it. However, in certain cases we may want to compare without converting a value, so we use three equal signs (the identity operator).

$string = "anything";  // notice that it's a string, not a truth value

if ($string == true) {  // or just if ($string)
  // this condition passes because PHP converts non-empty strings to true. If it was empty, it wouldn't pass
}

if ($string === true) {
  // this condition doesn't pass because we don't convert data types
}

An expression doesn't have to be only one value. A whole mathematical operation, such as addition, can also be an expression. In such cases, it's usually tested whether a value on the left is, for example, greater than a value on the right. But the whole thing is still one expression, which is evaluated (whether it's true or false) and according to that it's decided whether to run code.

$a = 5;
$b = 10;

if ($a + $b > 20) {
  // code won't run logically because 5 + 10 isn't greater than 20 and the expression is FALSE
}

This example is also abbreviated. If we store the expression in a variable, we get back to the beginning - we don't have to state == true

$a = 5;
$b = 10;
$result = $a + $b > 20;

if ($result) {
  // code
}

It's possible to evaluate a condition and at the same time store a value in a variable. But we have to enclose the expression in parentheses.

$a = 5;
$b = 10;
if ($result = $a + $b > 2)

Here, the result of the whole expression '$a + $b > 2' is stored in the $result variable, which will be TRUE. But we want to store a sum in the variable. We'll use parentheses to do so:

$a = 5;
$b = 10;
if (($result = $a + $b) > 2) {
  echo $result;  // it prints 15
}

Now the sum is stored in the variable first and only then it's evaluated whether it's greater than 2. This means that the $result variable contains a number 15 and we can work with it in the block.

The difference between NULL in the programming language and SQL

Both languages contain the NULL data type. But it works a little differently in both languages. E.g. in PHP it means 'empty', while in SQL it means 'unknown'.

In PHP, the expression:

NULL == NULL

evaluates to true because an empty value equals an empty value.

In SQL, however, this expression behaves differently. The result is again NULL, because does an unknown value equal to another unknown value? We don't know, so we can't determine whether it's TRUE or FALSE. Therefore, the result is again an 'unknown value', or NULL.

Casting variables

Casting variables in other words means changing its data type. Casting is often used, for example, in database queries, where we search by a specific ID. There are two ways to cast:

Using the function

The settype() function is used for this. The first parameter is a variable to be casted, and the second is the data type. It can be a boolean (shortly bool), integer (shortly int), float, string, array, object or null.

$number = 1;
$truthValue = settype($number, "bool");  // $number is now TRUE

$number = 0;
$truthValue = settype($number, "bool");  // $number is now FALSE

If, on the other hand, we want to find out the variable's data type, we use the gettype() function.

$number = 1;
echo gettype($number);  // integer

Using parentheses before an expression

Instead of functions, shorter notation using parentheses before an expression is more often used.

$number = 1;
$truthValue = (bool) $number;

As mentioned above, casting is often used, for example, in database queries, where we search by a specific ID. To make sure that we definitely pass a number to a database query, an input value can be cast.

$id = (int) $_GET["id"];

Now we don't have to worry about that there would be anything other than a number in the $id variable.

Sometimes casting is also used for simpler notation when manipulating an object instead of an array.

$array = array("key" => "value");
echo $array["key"];  // we must write parentheses, even quotes in some cases...

All we have to do is write an arrow to an object. For example, if we cast an array to an object in PHP, the stdClass class object is automatically created, where properties are like array keys.

$array = array("key" => "value");
$object = (object) $array;

echo $object->key;

// however, it can also be cast directly when creating an array
$object = (object) array(
  "key_1" => "value",
  "key_2" => "value"
)

Printing array elements

If you have already encountered the 'array' data type, you know that you can access its element with a key.

$array = array("key" => "value");
echo $array["key"];  // it prints 'value'

In this case, however, an error may occur if we try to print the element's value in a string.

echo "A string including $array["element"] some element in the array.";

In this example, the string ends immediately after the first bracket. It'll be followed by a set of characters that PHP doesn't understand and therefore throws an error. We have several ways to avoid the error.

// using apostrophes for a key
echo "A string including $array['element'] some element in the array.";

// ending the string
echo "A string including " .  $array["element"] . " some element in the array.";

// using braces (this method seems to me the best)
echo "A string including {$array["element"]} some element in the array.";

There is another option, and that's to omit quotes and apostrophes completely.

echo "A string including $array[element] some element in the array.";

However, I don't recommend this method to beginners, because it only works in a string. If we try to print the value separately:

echo $array[element];

it'll throw an error, because PHP will try to substitute a constant's value that doesn't exist.

Returning a truth value from a function

Due to the fact that no additional code is processed after the return statement, we can sometimes omit several lines. Let's look at the simple example:

function greaterThan($a, $b)
{
  $isGreater = $a > $b;
  if ($isGreater) {
    return TRUE;
  } else {
    return FALSE;
  }
}

The above is a primitive function that determines if the first parameter's value is greater than the value of the second. It returns TRUE or FALSE accordingly. However, the body of this function can be shortened to one line. How?

A) Removing else

Because no code is processed after the return statement, we can remove the else condition.

function greaterThan($a, $b)
{
  $isGreater = $a > $b;
  if ($isGreater) {
    return TRUE;
  }

  return FALSE;
}

If the condition is met, TRUE is returned and no further code is executed.

B) Removing if

Since we have the expression's result stored in the variable $isGreater, we can also remove the if condition.

function greaterThan($a, $b)
{
  $isGreater = $a > $b;

  return $isGreater;
}

C) Removing the variable

The given expression doesn't need to be stored in a variable at all and its result can be returned immediately.

function greaterThan($a, $b)
{
  return $a > $b;
}

Note: This is just an example of how code can be shortened, such a function would be unnecessary.

Storing a truth value in a variable

This is a very similar case to the previous example. Simple example:

if ($a + $b > 10) {
  $result = TRUE;
} else {
  $result = FALSE;
}

This code can also be shortened to one line. We can use, for example, a ternary operator.

$result = $a + $b > 10 ? TRUE : FALSE;

The ternary operator finds the expression's truth value, and if it's true, the expression after a question mark is used. On the other hand, if not true, the expression after a colon is used. If the resulting expression is a truth value, we can omit the expression after a question mark.

$result = $a + $b > 10 ?: FALSE;

In this example, however, it's possible to omit the ternary operator itself.

$result = $a + $b > 10;

That's all from the second part. The next part will focus more on working with data from a database - how to offload and how to transfer only data that we really need.


 

All articles in this section
Best Software Design Practices
Article has been written for you by Filip Smolík
Avatar
User rating:
1 votes
Activities