Suppose we want to find information about a student from a student list that contains a student in another section, so in this case RollNo alone may not produce the correct output. Therefore, we will need to find two values key = > in the list, which are equal to rollNO and section.Example :
// PHP search program several
// key = > pairs of values in an array
function
search (
$array
,
$search_list
) {
// Create array of results
$result
=
array
();
// iterate over each element of the array
foreach
(
$array
as
$key
= >
$value
) {
// Loop over each search term
foreach
(
$search_list
as
$k
= >
$v
) {
// If no array element occurs
// search condition then continue
// to next element
if
(! isset (
$value
[
$k
]) ||
$value
[
$k
]! =
$v
)
{
// Skip two loops
continue
2;
}
}
// Add array element key to
// array of results
$result
[] =
$value
;
}
// Return the result
return
$result
;
}
// Multidimensional array for the list of students
$arr
=
array
(
1 = >
array
(
’rollNo’
= > 44,
’name’
= >
’ Alice’
,
’section’
= >
’B’
),
2 = >
array
(
’rollNo’
= > 3,
’name’
= >
’ Amit’
,
’section’
= >
’ B’
),
3 = >
array
(
’rollNo’
= > 3,
’name’
= >
’ Bob’
,
’section’
= >
’ A’
),
4 = >
array
(
’rollNo’
= > 5,
’name’
= >
’ Gaurav’
,
’section’
= >
’ B’
),
5 = >
array
(
’rollNo’
= > 5,
’name’
= >
’ Gaurav’
,
’section’
= >
’ A’
)
);
// Define a search list with multiple keys = > value pair
$search_items
=
array
(
’rollNo’
= > 5,
’section’
= >
" A "
);
// Call the search and pass the array and
// search list
$res
= search (
$arr
,
$search_items
);
// Print search result
foreach
(
$res
as
$var
) {
echo
’RollNo:’
.
$var
[
’rollNo’
].
’
’
;
echo
’Name:’
.
$var
[
’name’
].
’
’
;
echo
’Section:’
.
$var
[
’section’
].
’
’
;
}
?>
Exit:
RollNo: 5
Name: Gaurav
Section: A