Create php variables from a single input

3656 views php

I have this input:

<input name="an_input" id="an_input">

An user write in the input field some words separated by comma.

Let's say he introduces milk, coffee, tea.

I want to create a php variable for each word:

$milk = "milk";
$coffe = "coffe";
$tea = "tea";

answered question

Why not use an array?

What have you tried? The explode() function seems useful here. Though an array seems a lot more practical than separate variables. What are you trying to accomplish with this?

1 Answer


You can try with list() and explode(). Lets try

    $user_input = 'milk, coffee, tea';
    list($milk, $coffee, $tee) = array_map('trim',explode(',', $user_input));
    echo $milk,$coffee, $tee;


OR If multiple comma separated value comes from input then you can do it using only the foreach()

 $user_input = 'milk, coffee, tea, biscuit, jam, jelly, nougut';
 $results =  array_map('trim',explode(',', $user_input));
 foreach($results as $result){
     ${$result} = $result;
 echo $tea;


posted this

Have an answer?


Please login first before posting an answer.