PHP get values from array by comma separated list

Issue

I’m trying to get a small piece of code to work, but i’m kind of stuck.

When people submit a form, it saves a few keywords, but in numbers, to prevent people from changing the input with inspect element.
Every keyword has it’s own number.

For example :

1 = test
2 = test2
etc.

When people submit the form, their input gets saved in a mysql database like this:

1, 2

What I’m trying to do from this point is I want to show keywords instead of numbers.
I’ve already made an array for the keywords:

$array = array(1 => 'test1', 2 => 'test2', 3 => 'test3', 4 => 'test4');

Is there a way to only show the values from the array that are the same as the numbers from the database?

Solution

First of all, you shouldn’t store serialized data in your DB. Normalize your data appropriately instead.

That said:

$fromDB = array_flip(array_map('trim',explode(',',"1, 2")));
$keyMap = array(1 => 'test1', 2 => 'test2', 3 => 'test3', 4 => 'test4');
$intersection= array_intersect_key($keyMap, $fromDB);

The $intersection variable will hold an array containing only those values from the $keyMap array which have corresponding keys in the $fromDB one.

http://php.net/array_intersect_key

Answered By – DanMan

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published