PHP

PHP function: implode()

Posted in PHP on December 8th, 2010 by Jason – Be the first to comment

I learned something new about the implode function the other day, namely that the order of the parameters does not matter. Ordinarily you would give the “glue” and then the array in that order, but the function will work the same if you provide them in reverse as well. I will just determine which is the string and which is the array and use the properly.

$glue = ",";
$array = array('hello', 'world');
echo implode($glue, $array) // echos hello,world
echo implode($array,$glue) // echos hello,world

PHP array_diff Quick Tip

Posted in PHP, Programming on October 19th, 2010 by Jason – 3 Comments

When using array_diff in php be sure to remember that this is a one way comparison. While this is not news, it is an easily overlooked part of the documentation for array_diff. It took me a few minutes the other day to figure out why my code was not working.

What this means? If you have {a, b, c} in array1, and {c, d, e} in array2, than array_diff(array1, array2) would produce a third array with the values {a, b} and not {a, b, d, e}. If instead you are needing to get the second set, so all the values that are not in both, there are a few options. This was my solution, though I am sure there are better ways out there.

$diff1 = array_diff($array1, $array2);
$diff2 = array_diff($array2, $array1);
$final = array_merge($diff1, $diff2);