I want to check if uri segment($sef) is in array, before sending id to database. And I want to ask which solution is better, or if is there something better.
Here are examples of how I tried to search the array
1)
if(array_search($sef, array_column($array,'sef'))) {
//find id and send it to DB
} else {
//wrong sef
}
2)
foreach($array as $k => $v) {
if( in_array($sef, $v)) {
return $v['id']; break;
} else {
//wrong sef
}
}
this is example of array
Array
(
[0] => Array
(
[sef] =>some-sef1
[id] => 39
)
[1] => Array
(
[sef] => some-sef2
[id] => 20
)
[2] => Array
(
[sef] => some-sef3
[id] => 38
)
Thanks for answers!
It depends on situation. For small size array, both of them will almost take same time.
1) If it's a small array, you can do it using in_array.
2) If it's a large array, You should use first one. Because a foreach will take more time to execute than array_search.
Both ways are almost the same, so it's a preference choice. There are some tweaks possible though. First:
$sef_ids = array_column($array, 'id', 'sef');
if (isset($sef_ids[$sef])) { $id = $sef_ids[$sef]; ... }
Second:
foreach ($array as $k => $v) {
if ($v['sef'] === $sef) { $id = $v['id']; ... }
}
Now first one looks faster (didn't check), but it's still micro optimization unless you work with large arrays. I would aim for having $sef_ids
data structure to work with from the beginning then.