PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 16, 2022

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

 May 16, 2022     laravel, php     No comments   

Issue

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


Solution

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:

  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.


Answered By - kingbeencent
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing