missing array items with PHP function array_diff()?

  • Thread starter Thread starter dhvrm
  • Start date Start date
D

dhvrm

Guest
You are probably iterating the array with a for loop, rather than a foreach.

<?php
$taken = array(1, 2, 3, 8, 9, 10, 11);
$avail = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32);
$result = array_diff($avail, $taken);

//notice that $result array is indexed
//with larger array's indexes;
print_r($result);
echo "<br>";

//$result array has 25 items;
//thus, using for loop restricted by count,
//only cells 1-25 are output;
//cells with address > 25 aren't included
for($i = 0; $i < count($result); $i++) {
echo "$result[$i], ";
}
echo "<br>";

//foreach returns all cells in array
//without regard for their index
foreach($result as $output) {
echo "$output, ";
}
?>
 
I have two arrays:

Taken: 1, 2, 3, 8, 9, 10, 11,

Total: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,

The operation I do on them is this:
$remaining = array_diff($total, $taken);

the return of printing $remaining is this:
Remaining: 4, 5, 6, 7, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,

Why are 26 through 32 missing?
Another example:

two arrays:

Range: 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
Taken: 1, 2, 3, 8, 9, 10, 11,

the operation I perform on them:
$selected = array_diff($range, $taken);

the output:
Selected: 7, 12, 13, 14, 15,

Why are 16 through 19 missing?
 
You are probably iterating the array with a for loop, rather than a foreach.

<?php
$taken = array(1, 2, 3, 8, 9, 10, 11);
$avail = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32);
$result = array_diff($avail, $taken);

//notice that $result array is indexed
//with larger array's indexes;
print_r($result);
echo "<br>";

//$result array has 25 items;
//thus, using for loop restricted by count,
//only cells 1-25 are output;
//cells with address > 25 aren't included
for($i = 0; $i < count($result); $i++) {
echo "$result[$i], ";
}
echo "<br>";

//foreach returns all cells in array
//without regard for their index
foreach($result as $output) {
echo "$output, ";
}
?>
 
Back
Top