Home php php get the key array

php get the key array [duplicate]

Author

Date

Category

There is an array

array (
  [47] = & gt; Array (
    [PageName] = & gt; Basic version
    [PageMeta] = & gt; Main.
    [betaid] = & gt;
  )
)

I want to get his key “47”, how to do it? The simplest checking on the value does not work

if (in_array ("Main", $ pages)) ECHO 123;

Answer 1

Search options.

by key:

reset ($ pages);
$ firstKey = Key ($ pages);
if (in_array ('Main', $ Pages [$ firstkey])) {
  // Found 'Main' ...
} else {
  // Didn't find 'Main' ...
}

Passage by array:

foreach ($ pages as $ key = & gt; $ value)
{
  If (in_array ('Main', $ Value)) {
    // Found 'Main' ...
  } else {
    // Didn't find 'Main' ...
  }
}

A more versatile method for checking values, suitable for nested arrays:

function check ($ array, $ value)
{
  Foreach ($ Array AS $ Key = & GT; $ inner) {
    If (IS_Array ($ Inner)) {
      if (check ($ inner, $ value)) {
        RETURN TRUE;
      }
    } else {
      if ($ value == $ inner) {
        RETURN TRUE;
      }
    }
  }
  RETURN FALSE;
}

Usage:

if (check ($ pages, 'main')) {
   // Found 'Main' ...
} else {
   // Didn't find 'Main' ...
}

Answer 2

You are looking for an array in the upper level, it will not work like that. And so it should:

foreach ($ pages as $ k = & gt; $ v) {
  if (in_array ("Main", $ V)) {
    Echo $ k;
    Break;
}
Previous articleDifferences FASM and MASM
Next articleSQL query error

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions