Dino Bic Boi
Dino Bic Boi

Reputation: 49

How to check if an array index contains a value

I have an array with some values in different spots. I want to check if there is a value in the index then put it in a new array starting at 0 then put in index 1 then next value at index 2 and so on. I need to shorten it and move them all to the left really.

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

The new array would be:

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

Maybe something like this:

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
    }
}

Upvotes: 0

Views: 157

Answers (5)

Cyclonecode
Cyclonecode

Reputation: 30071

To only get values that is not NULL or empty you could use array_filter() and array_values() like this:

$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);

Upvotes: 2

user4282834
user4282834

Reputation:

It's as simple as this: if ( $array [$i] ), and then put the value in another array with another counter that starts from 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);

Upvotes: 0

Ɛɔıs3
Ɛɔıs3

Reputation: 7853

If you want to check if an index has a value, do this :

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

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

Upvotes: 0

Try array_filter which makes exactly this

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

Upvotes: 0

Milad
Milad

Reputation: 28590

You can use

           array_filter($yourArray) 

It will remove all empty values for you

Upvotes: 0

Related Questions