Functions Archives

11 built-in PHP sorting options summarized and reference

PHP has 11 different built-in sorting options as of this writing and the manual, though offering good examples of how to use most of them, doesn’t really put them all on one single, quick summarized reference page. Here’s my attempt at doing just that.
sort - sort alphabetically (a-z) or numerically (0-9)
rsort - sort reverse-alphabetically (z-a) […]

get_defined_vars returns defined variables

Today in the #scriptschool chat we talked about how to get the current defined variables used in a script. Check out the following code which illustrates the use of get_defined_vars(). The variables set will be at the end of the output:

<?php
$myname = ‘TDavid’;
$mydomains = array(‘http://www.php-scripts.com’,‘http://www.tdscripts.com/’);
$arr = get_defined_vars();
echo ‘<pre>’;
var_dump($arr);
echo ”;
?>

This is particularly useful for keypoint checking/debugging.

Parsing names and numbers out of text

At one of our sites we needed to parse out some names and numbers from a log file. The strings also contained comment text and the order would be mixed format. These types of regular expression parsing can be tricky.
Let’s take a look at the two possible formats of the strings:
FORMAT #1:
[00:02:18][jvastine]7.52..I agree with […]

Using header to redirect the browser

The PHP header function allows redirection of the browser, among other cool things.
Example redirecting the browser to php-scripts.com homepage:

<?php
header(”Location: http://www.php-scripts.com/”);
?>

How to strip off last two characters from string using substr

substr comes in handy if you need to strip characters off the end of a string.

<?php
$test_string = ‘item 1, item 2, item 3, ‘;
$test_string = substr($test_string,0,-2);
echo($test_string); // returns “item 1, item 2, item 3″
?>

How to find the location of php.ini on the server

Using the phpinfo() function you can easily find the location of the php.ini file on the server. Here’s the code to generate the phpinfo information pictured above:

<?php
phpinfo();
?>

Shown with the red arrows in the screenshot above:
#1 - this is the version of PHP
#2 - these are the configured library. For example ‘–with-mcrypt=/usr/lib’ means the mcrypt library […]