Tag Archives: variable

PHP: Use REGEX to Ensure that your received Variable is a Number CodeUnit 20 MAY 2011

It is a good idea to check that the variables your script is receiving are in fact of the correct type in terms of value passed. For example, when receiving some sort of record ID value, 99% of the time we are expecting a numeric value. A simple method to ensure that the variable to be processed is indeed numeric, is through the use of a simple REGEX statement applied using the preg_replace PHP function.

As an example, let’s process a user ID passed to us via a POST to our script:

$userid = (key_exists('user-id', $_POST)) ? preg_replace("@[^0-9-]@", '', $_POST['user-id']) : '-1';

What the above does is first check that the user-id is indeed present in the $_POST variable. If it isn’t, set our internal variable to -1. If it is present, replace all characters that don’t fall within the set of 0 to 9, excluding dashes, with a blank. This is assigned back to our variable for internal use.

So a simple check to guarantee that we’ve received either a positive (2) or negative (-2) number!


PHP: Save print_r output into a Variable CodeUnit 10 MAR 2011

print_r() is an extremely useful PHP function that displays the information about just about any type of variable in a way that’s readable by humans. It is particularly essential for the display of arrays, making it often directed towards uncovering those all important system arrays of $_GET, $_POST, $_SERVER and of course, $_SESSION.

However the function by default prints out the information, sometimes not always the most useful of behaviours if you want to return its result as part of a function. However, not all is lost if you know about its second optional parameter, called $return.

$return is defaulted to false, meaning the function follows its default behaviour of printing out the information. However, if you set it to true, print_r() will in fact return what it would have printed as a string, perfect for stuffing into a variable and using elsewhere.

In practice:

$string = print_r($_GET,true);
echo $string;


Related Link: http://php.net/manual/en/function.print-r.php