Home > OS >  PHP array saving each character in a separate field instead of separating by the comma
PHP array saving each character in a separate field instead of separating by the comma

Time:08-17

Good day, new to PHP here

Using a form with a drop down, I want to send an array of 2 values, a Int and an String such as "[Int,String]",

however PHP is creating an array of each character which ends up ["[","i","n","t",",","s","t","r","i","n","g","]"]

On the PHP side, how do I get the array to only have the 2 elements, the int and string?

HTML:

<label ><b>Course: </b><span ></span><br></label>
<select name="course" id="course">
  <option id="0" value="" selected="" disabled="">« Please Select a Course »</option>
  <option id="1" value="[0,all]">All</option>
  <option id="2" value="[1,Course1]">Course1</option>
  <option id="3" value="[2,Course2]">Course2</option>
  <option id="4" value="[3,Course3]">Course3</option>
</select>

PHP:

$courseId = $_POST['course']; 
print_r ($courseId);

CodePudding user response:

I do not recommend you to treat an input value as an array, it's a string. You can split it on comma, example :

 <option id="0" value="0,all">All</option>
list($myInt, $myString) = explode(",", $_POST['course']);

// equivalent of 
$course = explode(",", $_POST['course']);
$myInt = $course[0];
$myString = $course[1];

CodePudding user response:

you can explode the string after you get the value:

<select name="course" id="course">
   <option id="0" value="" selected="" disabled="">« Please Select a Course »</option>
   <option id="1" value="0,all">All</option>
   <option id="2" value="1,Course1">Course1</option>
   <option id="3" value="2,Course2">Course2</option>
   <option id="4" value="3,Course3">Course3</option>
 </select>

in PHP like this:

$courseId = $_POST['course']; 
$arr = explode(',', $courseId);
print_r ($arr);

Result:

Array
(
    [0] => 1
    [1] => Course1
)
  • Related