Hello All,
We are talking about an issue which comes to PHP developers almost every day.
Say, we have an array:
$students = [
111 => ['id' => 111, 'name' = 'Philip'],
112 => ['id' => 112, 'name' = 'James'],
113 => ['id' => 113, 'name' = 'Stephen'],
....
];
Say this array has 100000 (one lack) rows.
And we are asked to loop over them and display names or other information.
What we will do it, we will loop over the array and print the records.
Fine up to here.
Second situation:
We need to check whether id 9989 is present in array.
How will you find it?
Way 1:
Through array_key_exists()
$studentId = 9899;
if (array_key_exists($studentId, $students)) {
// Code here
}
Way 2:
Set each student's array's key to its id like:
111 => ['id' => 111, 'name' = 'Philip'],
Now find it with isset()
$studentId = 9899;
if (isset($students[$studentId])) {
// Code here
}
Way 2 is much faster than way 1 as it is using in built language construct.
And through Way 1, we are traversing through whole array, where as through Way 2, we are just checking if an index is set.
No comments:
Post a Comment