0

Basically I have this array:

array(
  [0] => array("id" => "0", "header" => "img1"),
  [1] => array("id" => "4", "header" => "img4")
  [2] => array("id" => "6", "header" => "img6")
)

If I have $id = "4", how can I extract the index [1] to obtain "header" value?

3 Answers 3

1

You will want to do a foreach loop for this. But honestly if you structured your array indexes better than you could just to a simple isset test and then grab the value once you verify it is there.

The right way:

$headers = array(0 => 'img1', 4 => 'img4', 6 => 'img6');

if (isset($headers[$index])) {
  return $headers[$index];
}

Here is how to deal with it with your array (much more costly from a processing standpoint):

$headers = array(
  0 => array("id" => "0", "header" => "img1"),
  1 => array("id" => "4", "header" => "img4"),
  2 => array("id" => "6", "header" => "img6")
);

foreach ($headers AS $value) {
  if ($value['id'] == $index) {
    return $value['header'];
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Where $index being the ID you want to use.
Can't I obtain just the 0, 1 or 2 value?
Sure, as long as you have a way to know which index to pull/use then it doesn't really matter what the index is.
0
foreach ($array as $key => $value) {
    if ($value['id'] == '4') {
        echo $value['header'];
        break;
    }
}

It will be better to store id and header like this for example:

array(
    "0" => "img1",
    "4" => "img4",
    "6" => "img6",
);

2 Comments

Lol, we literally did just about the exact same thing.
I can't/don't want modify the structure, ids and headers comes from a DB
0

Arrays in PHP are actually hash tables behind the scenes, so accessing elements by key is extremely fast. If you can, change the way your array is created at the source to use the id (which I assume is unique) as the key, as already mentioned in other answers.

To transform your current array to be indexed by id, you could use this code:

$indexed = array();
foreach($array as $element) {
    $indexed[$element['id']] = $element['header'];
}
// $indexed now resembles id => header

You can then access header values in constant time using $indexed[$id].

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.