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',
    ),
);
1
  • 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. Commented Oct 2, 2020 at 14:49

2 Answers 2

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];
Sign up to request clarification or add additional context in comments.

3 Comments

is that the most efficient way? there isn't a one liner that would do the same thing?
I advise you to write and use understandable code and not one-liners, which can be sophisticated.
This is a good take on readability vs efficientcy stackoverflow.com/questions/183201/…
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;
      
   
}



?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.