I’ll start posting quick hints and tips that really saved my life and time while working on PHP (Either on Qlendar or other projects).
Why? Because KEEFY!!
No really, I’m just lacking materials so I’m making new ones.
Now to business.
Imagine this scenario:
You have two arrays of names and you want to merge them in one single array without duplicates.
For example, ArrayOne has [‘Ahmed’, ‘Bader’, ‘Jassim’] while ArrayTwo has [‘Ahmed’, ‘Hussein’, ‘Tariq’]. If you combine them together you get [‘Ahmed’, ‘Bader’, ‘Jassim’, ‘Ahmed’, ‘Hussein’, ‘Tariq’].
Instead of going on multiloops and stuff, here’s a simple line that resolves this issue:
$ResultArray = array_unique(array_merge($ArrayOne,$ArrayTwo));
And just to stretch it a bit more, lets say you have two arrays and some the values in either or both arrays are either false, null or simply empty. Traditionally, you’ll have to do loop in arrays, move the empty/null/false entries to the bottom, then use array_pop($ArrayWithUnwantedElements) to use array_pop() to remove whatever unwanted elements you have at the end of the array (Thats the smart way. The traditional way is to even do array_pop() part manually).
You don’t have to go through this hell. Here’s a simple line to do the magic:
$ResultArray = array_filter(array_unique(array_merge($ArrayOne,$ArrayTwo)));
This might be silly. But I actually spent around 30 minutes poking around with PHP’s arrays until I discovered these two functions which saved me a lot of work and headache (And lines of codes too!).
More PHP quickies to come 😀