php – Find array keys of a vector


I have an array where the "parent" indexes are not indexed with underlines and the children are indexed. Every time any parent receives a child, all other parents also receive a child.

Example we have 2 children:

  x = array()
  x_1 = array()
  x_2 = array()
  y = array()
  y_1 = array()
  y_2 = array()

I need to get all the indices that are parents, in this case x and y. The solution I found would be to traverse the vector looking for indexes that do not have underlines, but I didn't find a pretty solution, as I would have to traverse the vector one more time to add new children.

Would anyone have a simpler and/or prettier solution?


You can use preg_filter for this, so filter only where there is "no" underscore, or any other character.

By default the regex only returns data that exists, but there is a way to reverse this.

Well, overall this is it:


// Sua array!
$array = array(
  'x' => array(),
  'x_1' => array(),
  'x_2' => array(),
  'y' => array(),
  'y_1' => array(),
  'y_2' => array(),

// Filtro para apenas sem _
$filtro = preg_filter('/^((?!_).)*$/', '$1', array_keys( $array ));

// Exibe o $filtro

The return will be:

Array ( [0] => x [3] => y ) 

You can test this out by clicking here!

Scroll to Top