Given an array and an element, we have to find the occurrences of the element in the array.
To find the occurrences of a given element in an array, we can use two functions,
- array_keys()
It returns an array containing the specified keys (values).
- count()
It returns the total number of elements of an array i.e. count of the elements.
Firstly, we will call array_keys() function with the input array (in which we have to count the occurrences of the specified element) and element, array_keys() will return an array containing the keys, then we will call the function count() and pass the result of the array_keys() which will finally return the total number of occurrences of that element.
PHP code to find the occurrences of a given element
Output
Explanation:
Here, we have an array $array with the string elements and then assigning the element to $word to find its occurrences, as mentioned the above example, element "The" appears two times in the $array and element "Hello" doesn't appear.
need an explanation for this answer? contact us directly to get an explanation for this answer