如何输出哪个索引我在数组中找到一个元素

编程入门 行业动态 更新时间:2024-10-06 04:09:14
本文介绍了如何输出哪个索引我在数组中找到一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想遍历我的数组并查找它是否包含某些"searchWord",然后我想返回此searchWord存在的索引.我还想返回找到它的次数.

I want to loop through my array and find if it contains certain "searchWord", then I want to return which indexes this searchWord exists in. I also want to return how many times it's found.

这是我到目前为止所走的路,做了一个循环以返回"Yes"(是).或否"取决于是否找到它.但是,我该如何返回实际的索引&时间?

This is how far I've gotten so far, made a loop to return "Yes" or "No" depending if it's found or not. But how do I return the actual indexes & times?

(是的,我知道有一些功能,但是我想学习这是怎么做的.)

(Yes, I know there's some functions for this, but I want to learn how this is done.)

Enter random words: <input type="text" name="words" value="<?php echo isset($_POST['words']) ? $_POST['words']: '' ?>" ><br/> Search Word: <input type="text" name="search" value="<?php echo isset($_POST['search']) ? $_POST['search']: '' ?>" ><br/> <input type="submit" name="submit" value="Print" /> </form> <br> <?php $words = $_POST['words']; $array = explode(" ", $words); // Split words into array print_r($array); // Print $searchWord = $_POST['search']; foreach($array as $value) { if ($value == $searchWord) { echo "<br/>Yes"; //break; } else { echo "<br/>No"; //break; } } ?>

我希望它返回类似在索引0和4上找到2个单词我们"的字样"

I would like it to return something like "the word 'we' is found 2 times, on index 0 and 4"

推荐答案

为完整起见(无循环),只需搜索单词并返回键即可.然后,您可以对它们进行计数并显示它们:

For completeness (without a loop), just search for the word and return the keys. Then you can count them and display them:

$keys = array_keys($words, $searchWord); echo "the word '$searchWord' is found " . count($keys) . " times, on index " . implode(' and ', $keys);

更多推荐

如何输出哪个索引我在数组中找到一个元素

本文发布于:2023-07-04 09:21:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1022313.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我在   数组   索引   元素   中找到

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!