coolpasta
coolpasta

Reputation: 755

How do I match the value of an array to a key of another array in PHP?

I have 2 arrays, one of which is built dynamically and one which I use as a map.

The map array:

$social_links_map = [
    'twitter' => 'twitter-icon',
    'facebook' => 'facebook-icon'
];

And my dynamic array, which is just a simple list of social links:

$dynamic_social_links = [ 'twitter.com/me', 'facebook.com/me' ];
$social_links = explode( ',', $dynamic_social_links );

The $dynamic_social_links is an user input, as such, their input can be wrongly typed.

And I need to check if within my $social_links exists any of the $social_links_map keys and return the $social_links_map item accordingly:

if( !empty( $social_links ) ) {
    foreach( $social_links_map as $handle => $icon ) {
        foreach( $social_links as $social_link ) {
            if( strpos( $social_link, $handle ) ) {
                echo $handle;
            }
        }
    }
}

This doesn't allow for "duplicate removal", nor does it look very pretty. Any ideas?

Upvotes: 2

Views: 63

Answers (2)

Leigh Bicknell
Leigh Bicknell

Reputation: 872

Firstly, is it possible that you can allow the user to select from a list of your $social_links_map?

If not then the approach you are using is likely the simplest most readable way of doing this as there is no sure fire way to be able to match potentially random user input with a predefined array of options.

A couple of things to note:

As mentioned by le Mandarin, you can use array_unique to get rid of duplicates.

The other is that strpos will return 0 (which is falsey) if the search string (needle) is found at the very start of the context variable (haystack).

eg:

strpos('twitter.link/stuff', 'twitter');

will return 0 which is false Causing your if statement to fail.

instead try something like

if (false !== strpos('twitter.link/stuff', 'twitter')) {

Take note of the extra = in !==. This is necessary because you are saying "If the result is not exactly the boolean false.

Upvotes: 0

le Mandarin
le Mandarin

Reputation: 192

use

array_unique

to remove "duplicated data".

Try

$social_links = array_unique(explode( ',', $dynamic_social_links ));

Upvotes: 1

Related Questions