如何检查数组索引是否包含值


How to check if an array index contains a value

我有一个数组,在不同的地方有一些值。我想检查索引中是否有值,然后将其放入从 0 开始的新数组中,然后放入索引 1,然后在索引 2 处放入下一个值,依此类推。我需要缩短它并将它们全部移动到左侧。

Array ( [0] => 53 [1] => [2] => 55 [3] => 76 [4] => [5] => [6] => [7] => )

新数组将是:

newArray ( [0] => 53 [1] =>55 [2] => 76)

也许是这样的:

for ($i=0; $i < sizeof($questionWorth); $i++)
{ 
    if($questionWorth[$i] has a value)
    {
       put it in new array starting at index zero
       then increment the index of new array
    }
}

要仅获取不NULL或为空的值,您可以使用array_filter()array_values()如下所示:

$array = array(76, NULL, NULL, 56);
// remove empty values from array, notice that since no callback
// is supplied values that evaluates to false will be removed
$array = array_filter($array);
// since array_filter will preserve the array keys
// you can use array_values() to reindex the array numerically
$array = array_values($array);
// prints Array ( [0] => 76 [1] => 56 ) 
print_r($array);
您可以使用

           array_filter($yourArray) 

它将为您删除所有空值

尝试array_filter 正是这样

var_dump(array_filter(array(0 => 55, 1 => 60, 2 => null)))

如果要检查索引是否有值,请执行以下操作:

$variable = array ([0] => 53, [1] => , [2] => 55, [3] => 76, [4] => , [5] => , [6] => , [7] => )
foreach ($variable as $key => $value) {
        var_dump($key.' => '.$value);
    }

就这么简单:if ( $array [$i] ) ,然后将值放在另一个数组中,另一个计数器从 0 开始。

$array = array(76, NULL, NULL, 56);
$count = 0;
for ($i=0; $i < sizeof($array); $i++)
{ 
    if($array[$i])
    {
        $arr[$count] = $array[$i];
        $count++;
    }
};
print_r($array);
print_r($arr);