0

I have created an array of values and i'm wondering whether its possible to get the value of the parent item.

For example, if I have the value logo how can I retrieve that it belongs to FREE?

$widget_classes = array(
    'FREE' => array(
        'logo',
        'clock',
        'text',
        'rss',
        'rss marquee',
    ),
);
charlie
  • 415
  • 4
  • 35
  • 83
  • 1
    `array_key_first(array_filter($widget_classes, fn($v) => in_array('logo', $v)))` if you absolutely want a oneliner (PHP 7.3+). But seriously, use @u_mulder's solution (put it in a proper function/method), it's easier to read, and also more efficient as it will shortcircuit as soon as it finds the right key. – Jeto Oct 02 '20 at 14:49

2 Answers2

4

Iterate over your array considering keys, as FREE is the key:

foreach ($widget_classes as $key => $class) {
    if (in_array('logo', $class)) {
        echo $key;
    }
}

Here's a oneliner, make sure you understand what's going on here and how many iterations over arrays are performed:

echo array_keys(array_filter($widget_classes, function($v) { return in_array('logo', $v); }))[0];
u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • is that the most efficient way? there isn't a one liner that would do the same thing? – charlie Oct 02 '20 at 14:33
  • 2
    I advise you to write and use understandable code and not one-liners, which can be sophisticated. – u_mulder Oct 02 '20 at 14:37
  • 1
    This is a good take on readability vs efficientcy https://stackoverflow.com/questions/183201/should-a-developer-aim-for-readability-or-performance-first – IsThisJavascript Oct 02 '20 at 14:39
0

If your array becomes multidimensional like below then recursive function will help to find the parent of the value, but it will return the first matching.

    <?php

$widget_classes = array(
  'FREE' => array(
      'logo' => [ 
        'pogo', 
        'bunny' => [ 'rabbit' ]
      ],
      'clock',
      'text',
      'rss',
      'rss marquee',
  ),
);
 $parent = recursiveFind( $widget_classes, 'rabbit');
 var_dump( $parent );

 function recursiveFind(array $array, $needle) {

    foreach ($array as $key => $value) {
      if( is_array( $value ) ){
        $parent = recursiveFind( $value, $needle );
        if( $parent === true ){
          return $key;
        }
      }elseif ( $value === $needle ) {
        return true;
      }

    }
    return isset( $parent ) ? $parent : false;
      
   
}



?>
Al-Amin
  • 596
  • 3
  • 16