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
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:
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…
- Filter will use key and value for filtering by passing the flag
ARRAY_FILTER_USE_BOTHas third element on
- On the filtering process, the
$v(or value) shouldn’t be empty.
- Also on the filtering process, the
$k(or key) should have a
_filteron the end of the string.