We are now going to convert our pseudocodes to actual PHP 7 codes as shown:
function findABook(Array $bookList, String $bookName) {
$found = FALSE;
foreach($bookList as $index => $book) {
if($book === $bookName) {
$found = $index;
break;
}
}
return $found;
}
function placeAllBooks(Array $orderedBooks, Array &$bookList) {
foreach ($orderedBooks as $book) {
$bookFound = findABook($bookList, $book);
if($bookFound !== FALSE) {
array_splice($bookList, $bookFound, 1);
}
}
}
$bookList = ['PHP','MySQL','PGSQL','Oracle','Java'];
$orderedBooks = ['MySQL','PGSQL','Java'];
placeAllBooks($orderedBooks, $bookList);
echo implode(",", $bookList);
Let us now understand what is happening in the preceding code. First we have defined a new function, findABook at the beginning of the code. The function is defined with two parameters. One is Array $bookList and the other is String $bookName. At the beginning of the function we are initializing the $found to FALSE, which means nothing has been found yet. The foreach loop iterates through the book list array $bookList and for each book, it matches with our provided book name $bookName. If the book name that we are looking for matches with the book in the $bookList, we are assigning the index (where we found the match) to our $found variable. Since we have found it, there is no point in continuing the loop. So, we have used the break command to get out of the loop. Just out of the loop we are returning our $found variable. If the book was found, usually $found will return any integer value greater than 0, else it will return false:
function placeAllBooks(Array $orderedBooks, Array &$bookList) {
foreach ($orderedBooks as $book) {
$bookFound = findABook($bookList, $book);
if($bookFound !== FALSE) {
array_splice($bookList, $bookFound, 1);
}
}
}
This particular function placeAllBooks actually iterates through our ordered books $orderedBooks. We are iterating our ordered book list and searching each book in our delivered list using the findABook function. If the book is found in the ordered list ($bookFound !== FALSE), we are removing that book from the delivered book list using the array_splice() function of PHP:
$bookList = ['PHP','MySQL','PGSQL','Oracle','Java'];
$orderedBooks = ['MySQL','PGSQL','Java'];
These two lines actually shows two PHP arrays which are used for the list of books we have received, $bookList and the list of books we have actually ordered $orderedBooks. We are just using some dummy data to test our implemented code as shown:
placeAllBooks($orderedBooks, $bookList);
The last part of our code actually calls the function placeAllBooks to perform the whole operation of checking each book searching for it in our received books and removing it, if it is in the list. So basically, we have implemented our pseudocode to an actual PHP code which we can use to solve our problem.