How to store array elemnts in diffrent variables in php [duplicate]

帅比萌擦擦* 提交于 2020-01-07 06:57:41

问题


I have a select drop down list of languages and I'm intrested of putting each element of the array in diffrent variable. For you understanding my question I will put here a code:

<html dir="ltl">
<?php
header('Content-Type: text/html; charset=utf-8');
$db=mysqli_connect("localhost","root","","travelersdb");
mysqli_query($db,"SET NAMES 'utf8'");
?>

    <head>
            <link href="Styles/StyleEx.css" rel="stylesheet" type="text/css"/>
    </head>

    <script type="text/javascript">

         var expanded = false;

        function showCheckboxes() {
          var checkboxes = document.getElementById("checkboxes");
          if (!expanded) {
            checkboxes.style.display = "block";
            expanded = true;
          } else {
            checkboxes.style.display = "none";
            expanded = false;
          }
        }   
        </script> 
<body>


<tr>
      <td>Languages</td>
      <td dir="rtl">

          <form method="post" action="exxx.php">
          <div class="multiselect" dir="rtl">
          <div class="selectBox" onclick="showCheckboxes()" dir="rtl">
        <select>
        <option>Choose language:</option>
        </select>
        <div class="overSelect" dir="rtl"></div>
        </div>
        <div id="checkboxes">
        <label for="one">  
            <input type="checkbox"  id="one" name="languages[]" value="English">English</label>
            <label for="two">
            <input type="checkbox" id="two" name="languages[]" value="German" >German</label>
            <label for="three">
            <input type="checkbox" id="three" name="languages[]" value="French">French</label>
              <label for="four">
            <input type="checkbox" id="four" name="languages[]" value="Spanish">Spanish</label>
              <label for="five">
            <input type="checkbox" id="five" name="languages[]" value="Italien">Italien</label>
      </div>
  </div>  
              <input type="submit" name="submit">
          </form>

      </td>
      </tr>        

<?php

  if (isset($_POST['submit'])) {
 $languages = $_POST['languages'];


    $language1 =  $languages[0];
    $language2 =  $languages[1];
    $language3 =  $languages[2];
    $language4 =  $languages[3];
    $language5 =  $languages[4];

    echo $language1;
    echo $language2;
    echo $language3;
    echo $language4;
    echo $language5;
  }
?>

</body>
</html>

If I'm checking all the checkboxs there isn't a problem but if I'm checking less then 5 I will get this message:

Notice: Undefined offset: 

This is beacuse of the array size. How can I avoid this and echo the variables if there were less than 5 languages checked?


回答1:


You can use $$ to define a variable. check the live demo

Note you can access all the variable outside the foreach scope.

foreach($languages as $k => $v)
{
  $name = 'language' . ($k + 1);
  $$name = $v;
}

print_r($language1);



回答2:


Use loop. Simplest one would be foreach.

<?php
foreach ($_POST['languages'] as $lang) {
    echo $lang;
}
?>

since $_POST['languages'] is an array, you can loop through all of its elements. No matter how many are there. You even don't have to check if there are any elements at all, if there are none, foreach will be omitted.




回答3:


You should loop through the languages and create a variable variable.

for($i = 0, $cnt = count($languages); $i < $cnt; $i++) {
    $name = sprintf("language%d",$i+1);
    ${$name} = $languages[$i];
}

It will create $language1, $language2,.., but will create as many as the number of elements in the array(so it will create only 3 if 3 was checked)




回答4:


Try this..

  if (isset($_POST['submit'])) {
    if(count($_POST['languages'])>0){
        foreach($_POST['languages'] as $key=>$val){
            echo $val;
        }
    }
  }



回答5:


Using the advice from the answers above, I'd add the idea to use "variable variables" to allow you to name the individual variables from the $_POST array as they come in. To learn more about this technique, read the PHP documentation Also, be aware that there's an injection attack risk with this technique, so you need to have a way of checking that the elements from $_POST are what you're expecting.




回答6:


you can try this, foreach loop is better way to show/process arrays

if(!empty($_POST['languages']){
   $languages = $_POST['languages'];
   foreach($languages as $lang){
    echo $lang;
   }
}



回答7:


The proper way of doing this is using extract function. First you need to store in array where keys will be the name of variable and values will be the values of variable.

Try this code snippet here

<?php

ini_set('display_errors', 1);
$array=array();
foreach($languages as $key => $language)
{
    $array["language".($key+1)]=$language;
}
extract($array);
echo $language1;
echo $language2;


来源:https://stackoverflow.com/questions/43673876/how-to-store-array-elemnts-in-diffrent-variables-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!