Tuesday, June 5, 2007

PHP code Snippets, Algorithms, Array minus

There are hundreds of php snippets under the \lib\snippets\ directory of the Zend Studio Installation directory. I document them, write test cases and put them here.
The copyright of these code belongs to the original author. I publish them only for distributation purpose.
Function:
/**
* In this simple function you send two arrays
* and it gives you an array with the operation A-B,
* elements on A that are not included on B.
*
* @param array $vectorA
* @param
array $vectorB
* @return
array
*/
function RestaDeArrays($vectorA,$vectorB)
{
$cantA=count($vectorA);
$cantB=count($vectorB);
$No_saca=0;
for($i=0;$i<$cantA;$i++)
{
for($j=0;$j<$cantB;$j++)
{
if($vectorA[$i]==$vectorB[$j])
$No_saca=1;
}
if($No_saca==0)
$nuevo_array[]=$vectorA[$i];
else
$No_saca=0;
}
return $nuevo_array;
}


Test Code:
$vectorA = array(1,2,3,4,5,6,7,8);
$vectorB = array(2,4,6,8,10);
print_r(RestaDeArrays($vectorA,$vectorB));

output Result:
Array
(
[0] => 1
[1] => 3
[2] => 5
[3] => 7
)
?>