You pass it an array, and the term that you are looking for. It appears that it will assume that the array will only have numeric indexes, and for the specific purpose of this function/app, they are wanting to get the the index plus one.
Line by line for you:
Code: Select all
private function getIdInArray($array, $term)
{
This defined the function as private method within a class (meaning only other methods of the class can actually call it, you can't do something like:
$obj = new ThatClass(); $index = $obj->getInArray($ary,'item');
This function will take two parameters, the first will be assumed to be an array, the second is the item you are trying to find.
Code: Select all
foreach ($array as $key => $value) {
This loops through the array, during is iteration, the index of the current item is assigned to $key, and the value of the item is in $value
This checks to see if the value of the current item in the loop matches what was passed to the function to be looked for
this will only execute if it was a match, and it will return the index value plus 1. To be honest, this is kinda strange behavior, as it does not match the idea of the name of the function, since you are not getting the Index of the item, maybe it should be called
function getNextHigherIdInArray()...
This closes the loop for the foreach. While you don't specify it, after this point really you should be doing something like :
so that you are always returning a value, and can check against false to make sure something WAS found.
So basically, give the following array:
Code: Select all
$myArray = array( 'dog', 'cat', 'fish', 'hamster' )
searching for "cat" would return "2" even though it has an index value of 1. It is not good practive to depend on that association, better would be to actually set proper indexes:
Code: Select all
$myArray = array( 1=>'dog', 'cat', 'fish', 'hamster' )
(any non specified indexes will automatically use the next highest numerical index, so cat would be 2)
Then when you have the above, might as well just use the built in function
array_search() (see
http://php.net/array_search )