Click to See Complete Forum and Search --> : Working with arrays
lincolnway
08-19-2007, 01:14 AM
Here is what I am trying to do. I would like to single out a specific element or elements in an array. For example...
$a = Array("1", "2", "3");
$b = Array("1", "4", "5");
In this example I would like to pull the missing values from $a when compared to $b and place them into an array. So the results for the above two arrays would come out like this...
$c = Array("2", "3");
Basically whatever is missing in $a when compared to $b. Any ideas on how I can accomplish something like this. Any help or direction is appreciated.
Thanks
shane.carr
08-19-2007, 01:27 AM
Try this:
$a = array("1", "2", "3");
$b = array("1", "4", "5");
$c = array();
$i = 0;
while($i<count($a)){
if($a[$i]!=$b[$i]){
array_push($c, $a[$i]);
}
$i++;
}
I am assuming that $a and $b will be of the same length.
lincolnway
08-19-2007, 05:24 PM
Thanks for the reply. However, I don't think that will work for me. I believe it has to check the whole array to see if it exists. For example, what if I took that same code and changed the numbers around, it doesn't work. Hopefully this makes sense.
It will not only pull the 2 and 3 like it is suppose to but it pulls the 1 even though it is in both arrays.
$a = array("6", "10","1", "2", "3");
$b = array("1", "4", "5");
$c = array();
$i = 0;
while($i<count($a)){
if($a[$i]!=$b[$i]){
array_push($c, $a[$i]);
}
$i++;
}
bokeh
08-19-2007, 06:05 PM
Why not just use the built in functions?
array_diff() (http://www.php.net/array_diff)
shane.carr
08-19-2007, 06:06 PM
Try this then:
$a = array("6", "10","1", "2", "3");
$b = array("1", "4", "5");
$c = array();
$d = $a;
$i = 0;
while($i<count($a)){
$j = 0;
while($j<count($b)){
if($a[$i]==$b[$j]){
array_push($c, $a[$i]);
}
$j++;
}
$i++;
}
$i = 0;
while($i<count($d)){
$j = 0;
while($j<count($c)){
if($d[$i]==$c[$j]){
array_splice($d, $i, 1);
$i--;
break;
}
$j++;
}
$i++;
}
//$c will hold all of the alike values
//$d will hold all of the different values
shane.carr
08-19-2007, 06:14 PM
This is in reply to bokeh's post. I ran this code after running the code I made up:
print_r($d);
echo "<br />";
print_r(array_diff($a, $b));
Output:
Array ( [0] => 6 [1] => 10 [2] => 2 [3] => 3 )
Array ( [0] => 6 [1] => 10 [3] => 2 [4] => 3 )
They're exactly the same, except that PHP's built-in function seems to remove the "2" element in the array, without shifting back the "3" and the "4". Lincolnway, choose which code you like better. If you like to use while() loops to execute arrays, mine would be more compatible. If you prefer to use foreach(), either will be fine.
bokeh
08-19-2007, 06:33 PM
PHP's built-in function seems to remove the "2" element in the array, without shifting back the "3" and the "4".array_diff maintains the key/value pairs from the source array. If this is not what you want just re-key the array with array_values.$out = array_values(array_diff($a, $b));