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?
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'];
}
}
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",
);
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]
.