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

时间:2014-11-23 22:27:39

标签: php arrays

我有一个数组,在不同的位置有一些值。我想检查索引中是否有值,然后将它放在一个从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
    }
}

5 个答案:

答案 0 :(得分:2)

要仅获取非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);

答案 1 :(得分:0)

您可以使用

           array_filter($yourArray) 

它将删除所有空值

答案 2 :(得分:0)

尝试array_filter,这正是

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

答案 3 :(得分:0)

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

$variable = array ([0] => 53, [1] => , [2] => 55, [3] => 76, [4] => , [5] => , [6] => , [7] => )

foreach ($variable as $key => $value) {
        var_dump($key.' => '.$value);
    }

答案 4 :(得分:0)

就像这样简单: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);