Variable Handling Functions PHP

Posted on November 28th, 2022
Share this post:

Variable Handling Functions PHP

There are several variable handling functions in PHP, but in this article I will cover 4 that I use regularly when scripting. These examples are fairly basic, but should provide a good starting point for those looking to use them in order to increase the power of their PHP scripts.

Let's start with the 'gettype' function. Knowing the type of a variable is quite important. It can provide added security within scripts, as well as give the back end user more power over their content management system. Among other benefits, of course.


The above code block is quite basic, returning what each array value's variable type is. Within a browser the result is as below.

integer
double
NULL
object
string

It may look quite bare bones, but remember that from this point on one could use conditional statements and other tools in order to increase the functionality of a script.

The next function may look familiar, as it is used quite often. I have used it here on the site within a few articles. I thought it was important to cover it here as well.


Checking if something is an array can prevent unwanted errors, as well as provide much needed security within pages that are in the public eye. This is a basic code block as well, but provides a bit more power by using an if statement to check if our variables are within an array.

This is the result...

Yes, this is an array.

The next 2 examples are actually quite similar, however, each provides it's own functionality and limitations. The differences may be quite obvious within these examples, however, I will get into further detail about that at a later date.


The above code block checks to see if each of the variables within the array are numeric or not. This is fairly self-explanatory, I believe. The result...

17 is numeric.
no is not numeric.
246 is numeric.
type is not numeric.

Now we can take a look at the 'is_int' function. Make note that anything with single or double quotations will not be recognized as an integer without using other functions. Also, anything with a decimal point is not considered an integer. I can get into further examination of that later on.



1274 is an integer.
'28' is not an integer.
'98.25' is not an integer.
1965 is an integer.

Although these examples, again, are quite basic, you can probably see the potential for them to be taken to much higher levels of functionality. Like most functions with the language of PHP, using several at a time is always recommended. Still, having a basic knowledge of the most common variable handling functions is never a bad thing.

Posted on:
November 28th, 2022

Comments:

There are still no comments posted
Write a comment