PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, December 29, 2021

[FIXED] PHP: Search multidimensional array => get array_keys

 December 29, 2021     arrays, associative-array, multidimensional-array, php     No comments   

Issue

What's the best/fastest way to get the keys of an array by a search of a value in the 2nd level arrays?

$test = array(
    'name_01' => array('yellow', 'red', 'blue', 'black', 'white', 'purple'),
    'name_02' => array('red', 'blue', 'white', 'green'),
    'name_03' => array('blue', 'pink', 'purple', 'blue'),
    'name_04' => array('white', 'black', 'red'),
    'name_05' => array('yellow', 'white', 'pink', 'black')
);

For example the search by pink should return array('name_03', 'name_05')


Solution

A simple foreach() with in_array() is enough

$search = 'pink';

foreach($test as $key=>$arr){
   if(in_array($search,$arr)){
     echo $key.PHP_EOL;
   }

}

Output : https://3v4l.org/HVem8

If you want array as an output : https://3v4l.org/8e0sj



Answered By - Anant Kumar Singh
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing