PHP IndexOf Key like JavaScript
Many beginners to PHP wonder about how they use to do something in another language. One question that comes up often is, how do you use indexOf like in JavaScript in PHP? Well you can either use the following code or array_search function.
The indexOf function in JavaScript is used to find the number position of a letter in a string. The PHP equivalent is stristr().
However, in JavaScript, some browsers allow for indexOf() function which grabs the key index value of an array based on a searched value. If you don't have it, you can make it, and it looks like this:
Array.prototype.indexOf = function( v, b, s ) {
for( var i = +b || 0, l = this.length; i < l; i++ ) {
if( this[i]===v || s && this[i]==v ) { return i; }
}
return -1;
};
That code should add that function to the array objects. So that you can call var ind = MyArray.indexOf('text', 0, false);
However, in PHP you can also do something similar but with arrays, to grab the INDEX of an array, based on its VALUE.
Simply enter your needle or the value of the array you are looking for and the array haystack to search in. Example: $ArrayIndexNumber = indexOf($thisValue, $BigArray);
for($i = 0,$z = count($haystack); $i < $z; $i++){
if ($haystack[$i] == $needle) { //finds the needle
return $i;
}
}
return false;
}
The alternative is to use PHP's built-in array_search() function. However, array_search only returns the Key value, not the Key index number.
$keyName = array_search('apples', $array); // $keyName is 'fruit_2'
// do not expect array_search to work the same as indexOf.
Vidal (not verified)
indexOf in Javascript is a
indexOf in Javascript is a string function
Baran Ornarli
Clarified the tutorial, I
Clarified the tutorial, I think it's because some browsers don't allow the indexOf that I'm talking about here.
Post new comment