在给定的数组中查找一个数_PHP | 查找数组中给定元素的出现

在给定的数组中查找一个数

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()

    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.

首先,我们将使用输入数组(必须计算指定元素的出现次数)和元素调用array_keys()函数, array_keys()将返回包含键的数组,然后调用函数count()并传递array_keys()的结果,该结果最终将返回该元素出现的总数。

PHP code to find the occurrences of a given element

PHP代码查找给定元素的出现

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

在这里,我们有一个带有字符串元素的数组$ array ,然后将该元素分配给$ word来查找它的出现,如上面的示例所述,元素“ The”在$ array中出现了两次,而元素“ Hello”没有出现。

翻译自: https://www.includehelp.com/php/find-the-occurrences-of-a-given-element-in-an-array.aspx

在给定的数组中查找一个数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值