Skip to content

Instantly share code, notes, and snippets.

@jrivero
Created March 8, 2012 18:05
Show Gist options
  • Save jrivero/2002397 to your computer and use it in GitHub Desktop.
Save jrivero/2002397 to your computer and use it in GitHub Desktop.
Array reindex
<?php
// found at http://php.net/manual/en/function.array-filter.php
function array_reindex(array $source, $blacklist = array())
{
$i = 0;
foreach ($source as $key => $val) {
if ($key != $i) {
unset($source[$key]);
$source[$i] = $val;
}
$i++;
}
foreach ($source as $key => $val) {
foreach ($blacklist as $var) {
if ($val === $var) {
unset($source[$key]);
$source = reindex($source, $blacklist);
}
}
}
return $source;
}
// Examples:
// Create a simple array
$input = array(1 => 'red', 3 => 'green', 5 => 'blue', 7 => TRUE, 9 => FALSE, 11 => NULL);
// NOTE: If you have an array (look above) and your blacklist will look like this: array(TRUE, FALSE, NULL)
// Filter will delete array keys with value TRUE, FALSE or NULL
$blacklist = array(TRUE, FALSE, NULL);
// Output is: Array ( [0] => red [1] => green [2] => blue )
print_r( reindex($input, $blacklist) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment