[英]How to select several array elements and check if they are equal to variable
I'm trying to learn PHP on my own just by watching videos and reading blogs.我正在尝试通过观看视频和阅读博客自学 PHP。 I won't become a pro, I'm just a hobbyist.我不会成为职业选手,我只是个业余爱好者。 So I'm trying to code something but I got to a dead end.所以我正在尝试编写一些代码,但我走到了死胡同。 So I have a string, let's say the string has some numbers fe 100, 2000, 3000. Using the explode method I convert the string to an array.所以我有一个字符串,假设该字符串有一些数字 fe 100、2000、3000。使用 explode 方法我将字符串转换为数组。 Now I have a variable fe $var= 50;
现在我有一个变量 fe $var= 50;
I want to see if $var is equal to the first or the third element of the array;我想看看 $var 是否等于数组的第一个或第三个元素;
<?php
$str = " 100, 2000, 3000";
$fevArr = explode(",", $str);
$var = 50;
if ($var == $fevArr['0'] or $var == $fevArr['2'] ) {
echo "It is";
} else {
echo "It is not";
}
?>
However I might have a lot of numbers in the string and I may want to check if $var is eaqual to many of them (say to the 1th, 10th, 20th, 101th, 300th ect).但是我可能在字符串中有很多数字,我可能想检查 $var 是否等于其中的许多数字(比如第 1、10、20、101、300 等)。 So I wonder if there is a way to make soemthing like this:所以我想知道是否有办法制作这样的东西:
if ($var == $fevArr['0', '9', '19',]) {....
In other words if there is a way to select several array elements at once.换句话说,如果有办法一次 select 几个数组元素。
Yes you can use array_keys
function.是的,您可以使用array_keys
function。 It will return all the indices that match the value you want to look for.它将返回与您要查找的值匹配的所有索引。 Then you can use array_intersect
function to check whether those indices match your indices you want to look for.然后您可以使用array_intersect
function 检查这些索引是否与您要查找的索引匹配。
$var = 50;
$indices = [0, 2];
$keys = array_keys($fevArr, $var);
$matches = array_intersect($indices, $keys);
if(count($matches) > 0) {
...
}
You can use in_array($var, $fevArray)
( see documentation ) in your if
statement.您可以在if
语句中使用in_array($var, $fevArray)
(请参阅文档)。
in_array()
is not consistent just like this in_array()
像这样不一致
you can use the following code, I got it here你可以使用下面的代码,我在这里得到了
function contains($str, array $arr)
{
foreach($arr as $a) {
if (stripos($str,$a) !== false) return true;
}
return false;
}
and you can apply it as:您可以将其应用为:
if (contains($var, $fevArr) {
echo "It is";
}
else {
echo "It is not";
}
<?php
function contains_at_keys($haystack, $needle, $keys){
//get all keys matching needle
$matching_keys = array_keys($haystack, $needle);
//return if these keys contain one or more of the keys to search
return(sizeof(array_intersect($matching_keys, $keys)) > 0);
}
$str = "100, 2000, 3000, 50, 300, 50, 200";
$fevArr = explode(",", $str);
$var = 50;
$keys = [3, 5];
if(contains_at_keys($fevArr, $var, $keys)){
echo("It is");
} else {
echo("It is not");
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.