How can you replicate the .indexOf() function from Javascript in PHP?
To replicate the .indexOf() function from Javascript in PHP, you can use the strpos() function. strpos() function finds the position of the first occurrence of a substring in a string. It returns the position of the substring if found, and false if not found.
// Replicating indexOf() function from Javascript in PHP
function indexOf($haystack, $needle) {
$pos = strpos($haystack, $needle);
if ($pos === false) {
return -1;
} else {
return $pos;
}
}
// Example usage
$haystack = "Hello, World!";
$needle = "World";
echo indexOf($haystack, $needle); // Output: 7
Keywords
Related Questions
- Are there any alternative methods to include PHP files on a webpage if using tables is not working as expected?
- What are the best practices for passing data between multiple PHP pages using forms and dropdown menus?
- How can a beginner effectively start learning PHP to create a simple tree structure for displaying images and links?