skip to Main Content

I have a profile page where user can edit their profile, I have provided them a skill form where they can enter skill name & percentage of how much you are perfect in it like->

Skill1 percentage 86%  Add more

this add more button adds input field dynamically

So now when i try to save this data here is what i get in $_POST

$_POST['skill'];
$_POST['percentage'];

i tried adding them into array so that i can save it to database but because of multiple dynamic field it get messy & then here is what i receive in array

    Array
(
    [0] => Photoshop
    [1] => 55%
    [2] => PHP
    [3] => 35%
)

How can i easily know that this percentage is of this skill

Sometimes array looks like

Array
    (
        [0] => 55%
        [1] => Photoshop
        [2] => PHP
        [3] => 35%
    )

So how can i store dynamic field data into array so that later on it can be shown properly to the user

2

Answers


  1. Use an array format that you like:

    <input name='skill[0]'>
    <input name='percentage[0]'>
    <input name='skill[1]'>
    <input name='percentage[1]'>
    

    That will give you two arrays where the indexes match, for example:

    (
        [skills] => Array
            (
                [0] => Photoshop
                [1] => Word
            )
    )
    

    And:

    (
        [percentage] => Array
            (
                [0] => 65%
                [1] => 90%
            )
    )
    

    You could then use array_combine($_POST['skills'], $_POST['percentage']) to get something like:

    Array(
            [Photoshop] => 65%
            [Word] => 90%
         )
    

    You could use name='skill[] and name='percentage[] to create them dynamically instead of using numeric indexes, but if you ever try to do this with checkboxes it won’t work as you may think.

    Login or Signup to reply.
  2. you need to set an array of fields in your form if you want to pass multiple values, like:

    <input type="text" name="skills[]">
    <input type="text" name="percentage[]">
    

    and then in your php script:

    foreach($_POST['skills'] as $index => $value) {
      $skills[$value] = $_POST['percentage'][$index];
    }
    

    assuming that skills and percentage are arrays with the same size.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search