Codeigniter Multi-Dimensional Array Search

Codeigniter ships with an Array Helper, with three functions: element() to fetch an item from an array, random_element() to fetch a random element from an array, and elements() to fetch multiple items out of an array (to use like a filter). What it does not have, is a way to recursively search through a multidimensional array. We've solved this by extending our Array helper with this function recursive_element, which returns the key of it's associated value: /helpers/MY_array_helper.php
$value) {
      $current_key=$key;
      if($needle === $value 
        OR (is_array($value) 
          && recursive_element($needle,$value) !== false)) {
        return $current_key;
      }
    }
    return false;
  }
}
Then use as follows:
$my_things = array(
  'in_hand' => array(
    1 => 'pencil',
    2 => 'candy'
  ),
  'in_pocket' => array(
    1 => 'dollar',
    2 => 'gum',
    3 => 'stick'
  )
);

// Lets find out if we have any candy
$this->load->helper("array");
if (recursive_element("candy", $my_things) !== FALSE) 
{
  echo "I have candy!";
}
else
{
  echo "No candy here...";
}

// Results in "I have candy!"
Small dog web development studio

View All Our Posts

Web application developers in western Washington, creating user centric web solutions for businesses of all shapes and sizes.

Our projects include ecommerce, event organization, user driven web applications and more.


Small Dog Studios, LLC. Small Dog Studios News