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
CodePudding user response:
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! :D
Answering your question, what you need here is the knowledge of:
preg_match(...)
functionarray_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...
- Filter will use key and value for filtering by passing the flag
ARRAY_FILTER_USE_BOTH
as third element onarray_filter()
method. - On the filtering process, the
$v
(or value) shouldn't be empty. - Also on the filtering process, the
$k
(or key) should have a_filter
on the end of the string.