Reputation: 393
I currently have an array set up like this:
$u_id= array(
array(
NUM=>'2770', DESC=>'description one'
),
array(
NUM=>'33356', DESC=>'description two'
),
array(
NUM=>'13576', DESC=>'description three'
),
array(
NUM=>'14141', DESC=>'description four'
)
);
I need to be able to pass a number through this array as $num
(corresponding to a NUM=>'' in the array), and store the corresponding DESC=>'' as a string. For example, searching for "2770" would return "description one".
What would be the best way to go about doing this?
Upvotes: 1
Views: 112
Reputation: 51052
Are you constrained to this array structure? Because a more efficient structure would be to just do
$u_id= array(
'2770' => 'description one',
'33356' => 'description two',
'13576' => 'description three',
'14141' => 'description four'
);
That is to say, you just assume that the key is the number and the value is the description, rather than naming them explicitly. Then the code to find the correct description is just $u_id[2770]
(or whichever).
If that's not acceptable, you could also do
$u_id= array(
'2770' => array(
NUM=>'2770', DESC=>'description one'
),
'33356' => array(
NUM=>'33356', DESC=>'description two'
),
'13576' => array(
NUM=>'13576', DESC=>'description three'
),
'14141' => array(
NUM=>'14141', DESC=>'description four'
)
);
That is, the number is also used as the key to find the correct pair. The code to find the correct description becomes $u_id[2770]["NUM"]
.
In either of these scenarios, finding a given description from the number is a single step. If you can't change the array structure, though, then you'd have to loop through the array to check (which could take as many steps as there are items in the array).
Upvotes: 4
Reputation: 5520
foreach($arrays as $arr){
if($arr['NUM']==$num){
return $arr['DESC'];
}
}
Upvotes: 2