Create php variables from a single input

3656 views php
7

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

5

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

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

DEMO: https://3v4l.org/aXtA0

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

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

DEMO: https://3v4l.org/mdUdQ

posted this

Have an answer?

JD

Please login first before posting an answer.