Skip to content

How to find the desired element in the array and check whether it has a value or not?

I have a big array like this:

"twitter_link" => "http://twitter.com"
"twitter_text" => "text"
"youtube_link" => ""
"youtube_text" => ""
"snapchat_link" => "http://twitter.com"
"snapchat_text" => "text"
"linkedin_link" => ""
"linkedin_text" => ""

In this array, I need to find all all *_link keys and check if the value is set, then add all the keys where there is a value to another array

Answer

I would like to recommend you to read the following docs: https://laravel.com/docs/8.x/collections#available-methods, this may help you to find a multiple ways to iterate and alter an array if you don’t think the array_* methods from php are enough for your needs! 😀

Answering your question, what you need here is the knowledge of:

  1. preg_match(...) function
  2. array_filter(...) function using the flag: ARRAY_FILTER_USE_BOTH

You simply have to do the following:

$result = array_filter($links, fn($v, $k) => ($v !== "" && preg_match("/(_link)+$/i", $k)), ARRAY_FILTER_USE_BOTH)

And voilá, but what’s the explanation? Simply…

  1. Filter will use key and value for filtering by passing the flag ARRAY_FILTER_USE_BOTH as third element on array_filter() method.
  2. On the filtering process, the $v (or value) shouldn’t be empty.
  3. Also on the filtering process, the $k (or key) should have a _filter on the end of the string.