Posts tagged 'array'

Here’s a snippet that extracts elements from an array starting with a specific letter (alphabetical search).

$programming_languages = array('A+', 'A++', 'A# .NET', 'A# (Axiom)', 'A-0', 'B', 'Baja', 'BeanShell', 'C#', 'Cayenne', 'JavaScript', 'Java', 'JScript', 'Python', 'Perl', 'PHP', 'Visual Basic .NET', 'Visual FoxPro', 'ZOPL', 'ZPL');

function alpha_search($array, $letter = 'a') // 'a' is the default value
{
return array_filter($array, create_function('$var', 'return (strtolower(trim($var{0})) == strtolower("'.$letter.'"));'));
}

/* Values starting with 'A' */
echo '<pre>'; print_r(alpha_search($programming_languages, 'a'));  echo '</pre>'; 

/* Values starting with 'V' */
echo '<pre>'; print_r(alpha_search($programming_languages, 'v'));  echo '</pre>';

NOTE: In the second argument you can use either a lower case letter or an upper case letter. It’s case insensitive.

Here’s how our sample ouput will look like:

Array
(
    [0] => A+
    [1] => A++
    [2] => A# .NET
    [3] => A# (Axiom)
    [4] => A-0
)

Array
(
    [16] => Visual Basic .NET
    [17] => Visual FoxPro
)

PHP: Equivalent of trim() Function for Arrays

Posted on October 5, 2008, Filled under PHP,  Bookmark it

This function strips the null element values from the beginning and ending of an array. For instance, this snippet is useful when you use file(), which reads an entire file into an array and in the beginning / ending of the file there are blank lines that need to be stripped.

function trim_array($array, $keep_keys = false)
{
$i = 0;

   foreach($array as $key => $value)
   {
   $value = trim($value);

   if($value) break;

if($keep_keys) unset($array[$key]);

   $i++;
   }

if($i > 0 && !$keep_keys)
{
	array_splice($array, 0, $i);
}

$reverse = array_reverse($array, true);

$i = 0;

   foreach($reverse as $key => $value)
   {
   $value = trim($value);

   if($value) break;

   if($keep_keys) unset($array[$key]);

   $i++;
   }

if($i > 0 && !$keep_keys)
{
	array_splice($array, -$i);
}

return $array;
}

$array = array(' ', ' ' , ' ', "n", "r", 1, 2 , 5 , 7, ' ', ' ', ' ', 10, 11, 12, 13, ' ', "r", "n", " ", " ");

echo "<pre>"; print_r($array); echo "</pre>";

/*
First Argument: The Array
Second Argument: New keys? false = the current keys will be kept, true= new keys will be assigned to the array (default is set to 'false')
*/

echo "<pre>"; print_r(trim_array($array, true)); echo "</pre>";

NOTE: In the second argument of trim_array() you can specify if you wish to keep the initial array keys (true = will keep the keys, false = will assign new ones). The default value is ‘false’, meaning that new keys will be assigned to the array.

Display Values from an Array in Random Order

Posted on October 2, 2008, Filled under PHP,  Bookmark it

This is a function that randomizes the order of the elements in an array.

<?php
function randomize_array($array)
{
$rand_items = array_rand($array, count($array));

$new_array = array();

foreach($rand_items as $value)
	{
	$new_array[$value] = $array[$value];
	}

	return $new_array;
}

$array = array('sleep' => 'Delay execution',
                    'show_source' => 'alias for highlight_file()',
                    'str_ireplace' => 'PHP5 Function',
                    'sizeof' => 'Alias for count',
                    'parse_url' => 'Parse a URL and return its components');

echo "<pre>"; print_r($array); echo "</pre>";

echo "<pre>"; print_r(randomize_array($array)); echo "</pre>";

/*
-- Initial Array

Array
(
    [sleep] => Delay execution
    [show_source] => alias for highlight_file()
    [str_ireplace] => PHP5 Function
    [sizeof] => Alias for count
    [parse_url] => Parse a URL and return its components
)

-- An example of a random result

Array
(
    [sizeof] => Alias for count
    [parse_url] => Parse a URL and return its components
    [sleep] => Delay execution
    [str_ireplace] => PHP5 Function
    [show_source] => alias for highlight_file()
)
*/
?>

NOTE: A similar function in PHP is shuffle() which assigns new keys to elements in the array. It removes any existing keys that may have been assigned, instead of just reordering them as our randomize_array() function does.

PHP: How to remove empty values from an array

Posted on May 21, 2008, Filled under PHP,  Bookmark it

This function removes empty values from an array. This is useful if you’re working with dynamical arrays (for instance data harvested from a web site).

<?php
/*
Credits: Bit Repository
URL: http://www.bitrepository.com/web-programming/php/remove-empty-values-from-an-array.html
*/
function remove_array_empty_values($array, $remove_null_number = true)
{
	$new_array = array();

	$null_exceptions = array();

	foreach ($array as $key => $value)
	{
		$value = trim($value);

        if($remove_null_number)
		{
	        $null_exceptions[] = '0';
		}

        if(!in_array($value, $null_exceptions) && $value != "")
		{
            $new_array[] = $value;
        }
    }
    return $new_array;
}
?>

Example of usage:

$array = array("white", "yellow", 0, "green", " ", "navy");

$remove_null_number = true;
$new_array = remove_array_empty_values($array, $remove_null_number);

echo '<pre>'; print_r($new_array); echo '</pre>';

The new array will look like this:

Array
(
    [0] => white
    [1] => yellow
    [2] => green
    [3] => navy
)

NOTE: If you wish to keep the null number (0) then set the variable $remove_null_number to false.