Home » PHP » PHP Examples

PHP | Find the occurrences of a given element in an array

Finding occurrences of an element in an array: Here, we are going to learn how to find the occurrences of an element in the given array in PHP? For that, we are using array_keys() and count() functions of PHP.
Submitted by Bhanu Sharma, on August 10, 2019

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,

  1. array_keys()
    It returns an array containing the specified keys (values).
  2. 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

<?php
//an array of the string elements
$array = array(
    "The", 
    "Quick", 
    "Brown", 
    "Fox", 
    "Jumps", 
    "Right", 
    "Over", 
    "The", 
    "Lazy", 
    "Dog"
    );

//word/element to find the the array 
$word= "The";
//finding the occurances
$wordCount=count(array_keys($array, $word));
//printing the result
echo "Word <b>" .$word ."</b> Appears " .$wordCount ." time(s) in array\n";

//word/element to find the the array 
$word= "Hello";
//finding the occurances
$wordCount=count(array_keys($array, $word));
//printing the result
echo "Word <b>" .$word ."</b> Appears " .$wordCount ." time(s) in array\n";
?>

Output

Word The Appears 2 time(s) in array
Word Hello Appears 0 time(s) in array

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.







Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.