PHP Find the occurrences of a given element in an array

Discovering events of a component in an exhibit: Here, we will figure out how to discover the events of a component in the given cluster in PHP? For that, we are utilizing array_keys() and check() functions of PHP.

Given an exhibit and a component, we need to discover the events of the component in the cluster.

To discover the events of a given component in an exhibit, we can utilize two functions,

  • array_keys()
    • It restores an exhibit containing the predefined keys (values).
  • check()
    • It restores the complete number of components of an exhibit for example check of the components.

Initially, we will call array_keys() function with the information exhibit (in which we need to check the events of the predetermined component) and component, array_keys() will restore a cluster containing the keys, at that point we will call the function tally() and pass the consequence of the array_keys() which will at long last return the all out number of events of that component.

PHP code to discover the events of a given component

<?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

Clarification:

Here, we have a cluster $array with the string components and afterward allotting the component to $word to discover its events, as referenced the above example, component “The” seems multiple times in the $array and component “Hello” doesn’t show up.

Leave a Comment

error: Alert: Content is protected!!