1

I am trying to get a foreach loop to display all the values of an array but for some reason it skips value 4.

echo $sku."<br>";
$skuArray = explode(" ", $sku);
$skuCount = array_count_values($skuArray);
print_r($skuArray);
echo "<br><br>";
$i=0;
foreach ($skuCount as $key => $val) {
    echo "[".$i."] => ".$key." ";
    $i++;
}

and this is what the output looks like:

1DALI0SPBA775RW 2 $92.99 1GJESSGRIP10000 2 $9.99

Array ( [0] => 1DALI0SPBA775RW 
        [1] => 2 
        [2] => $92.99 
        [3] => 1GJESSGRIP10000 
        [4] => 2 
        [5] => $9.99 )

[0] => 1DALI0SPBA775RW 
[1] => 2 
[2] => $92.99 
[3] => 1GJESSGRIP10000 
[4] => $9.99

As you can see, the foreach loop says that 4 is equal to $9.99 but in the print_r array it is equal to 2 - which is what I expect it to be.

2
  • 4
    array_count_values sums the number of times a particular element appears in the array. Commented May 15, 2012 at 18:01
  • 1
    The issue is your foreach is looking at skuCount, why not do your foreach on skyuArray? Commented May 15, 2012 at 18:04

1 Answer 1

3

This is what you want:

echo $sku."<br>";
$skuArray = explode(" ", $sku);
print_r($skuArray);
echo "<br><br>";
$i=0;
foreach ($skuArray as $key => $val) {
    echo "[".$key."] => ".$val." ";
}

array_count_values($skuArray) actually creates an array you can loop through, but with duplicates elided to a single value. See the documentation.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.