PHP - Arrays Foreach Loops And Checkboxes
Hey forum,
I am a new php user and am having some issues (probably pretty basic to the likes of more experienced users), I am trying to make a script that has 4 checkboxes and a submit button, the values of the checkboxes should be passed through the array using a foreach loop, I got the basic template setup but when trying to pass the array I ran into a few problems. If anyone would take a peek at my code and point me in the right direction it would be much appreciated. Thanks forum. [attachment deleted by admin] Similar TutorialsHey forum, I am a new php user and am having some issues (probably pretty basic to the likes of more experienced users), I am trying to make a script that has 4 checkboxes and a submit button, the values of the checkboxes should be passed through the array using a foreach loop, I got the basic template setup but when trying to pass the array I ran into a few problems. If anyone would take a peek at my code and point me in the right direction it would be much appreciated. Thanks forum. Code: [Select] <html> <title>Toppings</title> <body> <p>What do you want on your pizza?</p> <form action="ProcessToppings.php" method="post"> <?php //define varialbes $Output_form = false; $submit = $_POST['submit']; if(isset($submit)) { if(empty($toppings)) { echo '<b>You forgot to choose a topping(s).</b>'; echo '<br>'; echo '<br>'; $Output_form = true; } else { $toppings=array("0", "1", "2", "3"); foreach ($toppings ['toppings'] as $order) { echo 'Your pizza will have these topping: ' . $toppings . '<br/>'; $Output_form = false; } } } ?> <input type="checkbox" name="toppings[0]" value="pepperoni" />Pepperoni<br /> <input type="checkbox" name="toppings[1]" value="sausage" />Sausage<br /> <input type="checkbox" name="toppings[2]" value="mushrooms" />Mushrooms<br /> <input type="checkbox" name="toppings[3]" value="olives" />Olives <p> <input type="submit" value="Place Order" name="submit" /></p> </form> </body> </html> I don't want to have to use two foreach loops. Code: [Select] foreach($verify_partners as $verified) { echo $verified; echo $id; if ($verified == $id) { ?> <div> Remove </div> <?php } } It prints out as Array6Array6 My goal here is to have it foreach group from the DB it'll create a new frameset with the groupName as the legend and then under each of those it will create another foreach for each of the fields inside of that group that has a enabled value of 0 from the db. Both queries work correctly. I just get trouble writing foreach loops and I'm not sure how this one is going to work out. Code: [Select] <?php session_start(); // Access the existing session // Include the database page require ('../../inc/dbconfig.php'); $defaultCharID = $_SESSION['defaultCharID']; $styleIDQuery = " SELECT characters.styleID FROM characters WHERE characters.ID = '" . $defaultCharID . "'"; $styleIDResult = mysqli_query ( $dbc, $styleIDQuery ); // Run The Query $row = mysqli_fetch_array( $styleIDResult, MYSQL_ASSOC ); $styleID = $row[ 'styleID' ]; $biofieldsQuery = " SELECT fields.*, groups.* FROM fields INNER JOIN groups ON fields.groupID = groups.ID WHERE groups.styleID = '" . $styleID . "' AND fields.styleID = '" . $styleID . "' AND groups.enabled = 0 AND fields.enabled = 0"; $biofieldsResult = mysqli_query ( $dbc, $biofieldsQuery ); // Run The Query $row = mysqli_fetch_array( $biofieldsResult, MYSQL_ASSOC ); $groupName = $row[ 'groupName' ]; ?> <script type="text/javascript"> $(document).ready(function() { }); </script> <!-- Title --> <div id="title" class="b2"> <h2>Character Management</h2> <!-- TitleActions --> <div id="titleActions"> <!-- ListSearch --> <div class="listSearch actionBlock"> <div class="search"> <label for="search">Recherche</label> <input type="text" name="search" id="search" class="text" /> </div> <div class="submit"> <button type="submit" id="search-button" class="button"><strong><img src="img/icons/search_48.png" alt="comments" class="icon "/></strong></button> </div> </div> <!-- /ListSearch --> </div> <!-- /TitleActions --> </div> <!-- Title --> <!-- Inner Content --> <div id="innerContent"> <form action="#" id="bioForm" > <fieldset> <legend><?php echo $groupName; ?></legend> <div class="field required"> <label for="matchType">Match Type Name</label> <input type="text" class="text" name="matchType" id="matchType" title="Match Type Name"/> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <input type="submit" class="submit" name="submitMatchType" id="submitMatchType" title="Submit Match Type" value="Submit Match Type"/> </fieldset> </form> </div> <!-- /Inner Content --> Hi Guys, I'm really [confused] about this however what I have so far is create a simple HTML form, instructing the end user to enter a list of keywords with links to replace them with in the following format: A keywords followed by a comma and then URL and semicolon: For example: birds,http://www.birdwatching.com/; snakes,http://www.whales.com/; horses,http://www.horse.com/; What I have done next is split each word with its associated url after each newline and then placed all the words into 1 array and all the urls into another array, using the following code: preg_match_all('/(.*),(.*);/',$wordsurls, $phrase); $wds = $phrase[1]; $rurls = $phrase[2]; foreach($wds as $wd) { $words_array[] = $wd; } foreach($rurls as $rurl) { $urls_array[] = $rurl; } All that works perfectly fine but now I wish to search a string to find each of those keywords, and if they exist I would like to replace them with the URL. I believe this can be done using Parallel Array matching but do not know how to go accomplishing this. Could someone please help me? Thank you in advance. M Hello, lately I have been having a problem with my simple PHP script. Out of the blue the following script doesnt seem to work properly, function sanitize_tags($content, $bad_tags = '') { foreach ($bad_tags as $tag) { $stripped_tags = str_replace($tag, '', $content); return $stripped_tags; } return $content; } $contents = "<html> <head> </head> <body>yutu<style>ghghl;kl;<script>hfjhk </body> </html>"; $bad_tag = array("<style>", "<script>"); $sanitize = sanitize_tags($contents, $bad_tag); echo $sanitize; Basically, when the function is invoked, only the first element in the array is used by the function. It seems like the second+ elements arent even iterated. Why is it only the first element is iterated? I have a feeling its going to be something extremely obvious. Thanks in advance. I know there's something wrong with my code because the page never loads so there's somethign wrong with either the for loop or foreach loop. The topRankings variable is set correct and giving the right value. Code: [Select] <?php for ($i = 0; $i >= count($topRankings); $i++){ foreach($topRankings[$i] as $k=>$v) { $seperator = ($elements == $count) ? '' : '<hr />'; $name = (!isset($row['character_name'])) ? 'TBD' : $row['character_name']; $count++; ?> <li><span class="red"><?php echo $name; ?></span></li> <?php } } ?> I'm trying to build a tree to display product groups, but I can't achieve what I want. There is a hierarchy for the tree which I need to follow:
1H I want to list all the categories (1H) with its subcategories(1HS), and it's subcategories (1HSMP). This is the code I'm currently using: <ul> <?php //Here we fetch category $categories_list = array(); if($stmt = $conn -> prepare("SELECT a.category, a.subcategory, a.subcategory1, a.category_description, a.subcategory_description, a.subcategory_description1, SUM(nsq.sales_amount) AS sales, SUM(nsq.sales_amount+nsq.cost_amount) AS RUC FROM dpb.articles a LEFT JOIN dpb.nav_sales_qty nsq ON nsq.article_no = a.article_no WHERE nsq.entry_type_desc = 'Prodaja' GROUP BY a.subcategory1")) { $stmt -> execute(); $stmt -> store_result(); $stmt -> bind_result($category, $subcategory, $subcategory1, $category_description, $subcategory_description, $subcategory_description1, $total_sales, $total_profit); while($stmt -> fetch()) { $categories_list[] = array('category' => $category, 'subcategory' => $subcategory, 'subcategory1' => $subcategory1, 'category_description' => $category_description, 'subcategory_description' => $subcategory_description, 'subcategory_description1' => $subcategory_description1, 'total_profit' => $total_profit, 'total_sales' => $total_sales); } $stmt -> close(); } foreach($categories_list as $key => $value) { ?> <li><?php echo $value['category'].' - '.$value['category_description']; ?> <ul> <?php //Here we filter subcategory if(strpos($value['subcategory'], $value['category']) === 0) { //Iterate over subcategory foreach ($value as $key2 => $value2) { debugVar($value2); ?> <li data-jstree='{"opened":true}'><?php echo $value2['subcategory'] . ' - ' . $value2['subcategory_description']; ?> <ul> <?php //Here we filter subcategory2 if (strpos($value['subcategory1'], $value['subcategory']) !== false) { ?> <li data-jstree='{"type":"file"}'> <?php echo $value['subcategory1']; ?> </li> <?php //Here we close subcategory1 if statement } ?> </ul> </li> <?php //Here we close subcategory if statement } } ?> </ul> </li> <?php //Close foreach loop } ?> </ul> The result I'm getting is attached in the photo, and it's not what I want! The result I need is the following: I find a category (1H), and then I find all of its subcategories which are 1H% (all that start with 1H) and display them bellow 1H. Then I iterate over all of these subcategories (example 1HS%, 1HP%, 1HRD%) and I find all of their subcategories which are starting with (1HS, 1HP, 1HRD) and display them. Example:
1H Can you please help me how to achieve that? I spent a lot of time, and I can't get the proper result.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Second Testing</title> <link href="styler.css" rel="stylesheet" type="text/css" /> </head> <body> <?php error_reporting(0); $num_rows = 16; $number1 = 4; $inn = array(7,10,13,16); $outt = array(14,16,21,23); $numm = array(3,5,7,9); $r_time_in = min($inn); for($i = 0; $i <= $num_rows; $i++) { $new_r_timer_in[$i] = $r_time_in; $new_r_timer_out[$i] = $new_r_timer_in[$i] + 1; $r_time_in += 1; } // for($y = 0; $y <= $number1; $i++) // { // for($i = 0; $i <= ($num_rows - 1); $i++) // { // if(($inn[$y] <= $new_r_timer_in[$i]) || ($outt[$y] <= $new_r_timer_out[$i])) // { // $numb[$i] = $numm[$i] + $numm[$i - 1]; // } // else // { // $numb[$i] = $numm[$i - 1]; // } // } // } for($i = 0; $i <= ($num_rows - 1); $i++) { echo '<table width="526" border="0"><tr> <td width="169"> <input type="text" name="$r_in[]" value="'.$new_r_timer_in[$i].'" style="width:169px" readonly="readonly" class="text_non_color"/></td> <td width="169"> <input type="text" name="$r_out[]" value="'.$new_r_timer_out[$i].'" style="width:169px" readonly="readonly" class="text_non_color"/></td> <td width="169"> <input type="text" name="$r_num[]" value="'.$numb[$i].'" style="width:169px" readonly="readonly" class="text_non_color"/></td>'; } print("</tr>"); ?> </body> </html> the code above works very well in its current state. three columns are produced but only two have data, the third column is empty. when executed, the code is supposed to check whether a range(7 - is between the first element of array $inn and the first element of array $outt and then add the corresponding number in array $numm to the number in that(7 - range the commented out code is supposed to implement this idea but its not.........help. Code: [Select] $query = "SELECT * FROM Companies WHERE owner = '$userName'"; $result = mysql_query($query) or die("Error: " . mysql_error()); $count = mysql_num_rows($result); echo("Count: $count<p>"); $result = mysql_query("SELECT name FROM Companies WHERE owner = '$userName'") or die("Error: " . mysql_error()); $result = mysql_fetch_row($result); for ($i=0; $i<=$count; $i++){ // $i<=$count means do while $i is less than or equal to $count /$companyName[$i] = $result[$i]; echo("$i: $companyName[$i]<br />"); echo("$i: $a<br />"); } I am trying to check the number of entries of company names the user has in the table Companies. I am then trying to use a for loop to loop through and store each of those names into an array. It doesn't work and I don't know why, can anyone see my problem? I've got a page that has a dynamic number of checkboxes. I'm trying to figure out how to process the form once submitted. I've got a foreach loop set up, but I need to know the id of the checkbox so that I can make the change to my database accordingly. At the moment, my form is built with the checkboxes given the name of "checkbox['$id']", where id is pulled from the database. In my parsing script, I've got this foreach loop that I found on the internet Code: [Select] foreach($_POST["checkbox"] as $checkbox){ } But I don't know what to put in that foreach loop to be able to grab the id that the checkbox was given when the form was initially built? I'm struggling to find any examples on the Internet :/.. Denno Excuse my late night slop! But I read a thread earlier and I am working on a dynamic way to address checkboxes with some intuitive messages while processing, and I cannot get this to work right w/out errors.. Any ideas where I am going totally wrong with this? <form name="" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> One <input type="checkbox" name="checkbox[]" value="checkOneValue" /><br /> Two <input type="checkbox" name="checkbox[]" value="checkTwoValue" /><br /> Three <input type="checkbox" name="checkbox[]" value="checkThreeValue" /><br /> Four <input type="checkbox" name="checkbox[]" value="checkFourValue" /><br /> Five <input type="checkbox" name="checkbox[]" value="checkFiveValue" /><br /> <input type="submit" name="submit" value="Echo Checkbox Data!" /> </form> <?php if (isset($_POST['submit'])) { $checkbox = $_POST['checkbox']; foreach ($checkbox as $checkboxValue) if (empty($checkboxValue)) { echo "$checkboxValue is emtpy"; } else { echo "<br>$checkboxValue is checked"; } }; ?> When no checkboxes are selected, I am dealing with this S%#$! Otherwise it works as intended.. Notice: Undefined index: checkbox in C:\wamp\www\php_practice\0\checkbox_echoing_1.php on line 24 Warning: Invalid argument supplied for foreach() in C:\wamp\www\php_practice\0\checkbox_echoing_1.php on line 26 Hey all.. I have been messing around with some code with a form that has checkboxes on them, and the option of selecting more than one checkbox to submit to the database. However, I keep getting the error," Warning: Invalid argument supplied for foreach() in (mydirectory)". I have followed many tutorials and I don't see anything I am doing differently that they are, so I'm sure this is a simple fix, of something I am overlooking, or I am just horrible at this (new person). Here is the snippet of the HTML code for the checkboxes. Code: [Select] <label> <input type="checkbox" name="project_list[]" value="chat"/> Chat Project (age 18+ requirement)</label> <br /> <label> <input type="checkbox" name="project_list[]" value="forums"/> Forums Project (age 18+ requirement)</label> <br /> <label> <input type="checkbox" name="project_list[]" value="content"/> Content/Editorial Project (postcasts, blogging, etc.)</label> <br /> <label> <input type="checkbox" name="project_list[]" value="technology" /> Technology Project</label> <br /> <label> <input type="checkbox" name="project_list[]" value="marketing"/> Marketing, Promotions and Publicity</label> <br /> <label> <input type="checkbox" name="project_list[]" value="designartwork"/> Design and Artwork</label> Here is the PHP code that I am using to do this. Code: [Select] include 'db.php'; mysql_select_db('skylers_training'); if($_POST['submit']) { $project_lists = $_POST['project_list']; foreach($project_lists as $list); //This is the line the code is getting the error on. And the section of the INSERT MYSQL CODE for this part. Code: [Select] $reginsert = mysql_query("INSERT INTO ... // the rest of the code (that works fine) follows this. '$list' // This is the line that is supposed to send data from the checklists to the database. When I submit the form, in addition to the error, nothing is submitted to the database table for the list (everything else works fine). Any insight into this, would be appreciated. Thanks! Hi, I have a set of checkboxes a bit like a checklist and I then want the items that aren't checked to displayed. On the first page, I have this code: <? while($row = mysql_fetch_array($result)) { ?> <form action="packed.php" method="post"> <div> <label><input type="checkbox" name="<? echo stripslashes($row['checklistitem']); ?>" value="yes"> <? echo stripslashes($row['checklistitem']); ?> </label> </div> This basically takes an array from a database. The info is then posted to the next page which hopefully will display the boxes which are 'unticked' or unchecked if you will. The code I have on the second page is: <?php $query_string = ""; if ($_POST) { $kv = array(); foreach ($_POST as $key => $value) { $kv[] = "$key"; } $query_string = join("<br />", $kv); } else { $query_string = $_SERVER['QUERY_STRING']; } echo $query_string; ?> At the moment, it returns the array items that were checked but I want the unchecked ones to be shown. Is that possible? Thanks very much! -Steve for starters, i am a complete beginner at PHP, so i know almost nothing.
so, the basic outline is that i am required to create a table with 2 columns, and use PHP where i can
so the first set of code lays down the table and the ability to type in text of "name" and "surname". ----i think this "input" is HTML, yes?? is there a way to enter it as PHP?
<table border=\"2\"> <tr><th><b>Requirements</b></th><th><b>Selections</b></th></tr> <tr><td>Name</td><td><input type="text" name="name"/></td></tr> <tr><td>Surname</td><td><input type="text" name="surname"/></td></tr>so, for this next section, adding on is the part for "age". i want this to appear as a dropdown selection. i've written PHP where possible, however this does not work when opening the file in a browser. it simply leaves a blank dropdown menu with no options. ???? <tr><td>Age</td><td><select> <?php for ($num=11; $num<=22; $num++){ echo '<option>' .$num. '</option>'; } ?> </select>lastly, i have the part for "activity choice". this again i believe i wrote the radio buttons in HTML??? am i able to write this as PHP???? <tr><td>Activity Choice</td><td><input type="radio" name="activityChoice" value "music"/> Music ($30.00)<br> <input type="radio" name="activityChoice" value "swimming"/> Swimming ($25.50)<br> <input type="radio" name="activityChoice" value "tennis"/> Tennis ($20.00)<br> <input type="radio" name="activityChoice" value "basketball"/> Basketball ($15.50)<br> <input type="radio" name="activityChoice" value "netball"/> Netball ($15.50)<br> <input type="radio" name="activityChoice" value "dance"/> Dance ($10.50)<br> <input type="radio" name="activityChoice" value "communityService"/> Community Service (No Charge)</td></tr> Hello , I have a table like $data[$var][$i] $data is an string, $var is a string and $i is an index int. I am tired to write for($i=1;,$i<=count($$data[$var],$i++) { echo $data['id'][$i] ... }oouuuff How i can make it with foreach ? I tried foreach ($data -> $field as $value) echo $value; but i doesnt work. Any advise ? How do i ouput it like this Code: [Select] Array ( [Griffin] => Array ( [0] => Peter [1] => Lois [2] => Megan ) [Quagmire] => Array ( [0] => Glenn ) [Brown] => Array ( [0] => Cleveland [1] => Loretta [2] => Junior ) ) rather than this Code: [Select] Array ( [field_name] => first_name [field_type] => 1 [max_length] => 20 ) Array ( [field_name] => last_name [field_type] => 1 [max_length] => 40 ) Array ( [field_name] => email [field_type] => 1 [max_length] => 80 ) Code: [Select] $fields = array(); foreach ($_POST['use'] as $field){ $fields = array( "field_name"=>$field, "field_type"=>$match_types[$i], "max_length"=>$match_length[$i]); print_r($fields); echo $fields[0]['field_name']; //echo $field.' - Type: '.$match_types[$i].' - Lenght: '.$match_length[$i]."<br />"; $i++; } I have two arrays as Code: [Select] $array1=array("word1","word2","word3"); $array2=array("term1","term2","term3"); How can I have a foreach loop to echo "word1-term1", "word2-term2", .... I mean having Code: [Select] echo "$array1[0]-$array2[0]";but in a foreach loop Hi everyone, If you take a look at my code below I am having trouble echoing the key/ value pair of the 'sex' array which is a sub array of 'pens'. I have tried so many different ways but to no avail, thanks Chris! Code: [Select] <?php $products = array( 'paper' => array( 'copier' => "Copier & Multipurpose", 'inkjet' => "Inkjet Printer", 'laser' => "Laser Printer", 'photo' => "Photographic Paper"), 'pens' => array( 'ball' => "Ball Point", 'hilite' => "Highlighters", 'marker' => "Markers", 'sex' => array ( 'condom' => "Protection")), 'misc' => array( 'tape' => "Sticky Tape", 'glue' => "Adhesives", 'clips' => "Paperclips") ); echo "<pre>"; foreach ($products as $section => $items ) foreach ($items as $key => $value) echo "$section:\t$key\t($value)<br>"; echo "</pre>"; ?> Let me explain my problem. I have an array with dates and numbers in format ($cronograma) Ex: Array ( [2020-09-21] => Array ( [0] => 2020-09-21 [1] => 2 [2] => 2 [3] => 2 ) [2020-09-28] => Array ( [0] => 2020-09-28 [1] => 2 [2] => 2 [3] => 4 ) Then i have another array with 2 ids (in this case 58,60) ($id) Finally i have a third array with numbers only (in this case 34,34) $tot So what i want is cross information beween them, for example for id 58 I must get dates (first element and last element when $tot = 34) for id 60 I must get dates (first element after $tot =34 and last element of array) Whath i have so far is this foreach ($id as $idPlan) { foreach ($cronograma as $c) { $t1 = 0; foreach ($tot as $d) { $t1 += (int)$d['tempos']; if ($c[3] == $t1) { $newAr[] =$idPlan; $newAr[] = $c[0]; } } } } My response array(8) { [0]=> string(2) "58" [1]=> string(10) "2021-02-01" [2]=> string(2) "58" [3]=> string(10) "2021-06-14" [4]=> string(2) "60" [5]=> string(10) "2021-02-01" [6]=> string(2) "60" [7]=> string(10) "2021-06-14" } null So it's clear that i have all repeated I should have a line like: 58 - 2020-09-21 -2021-02-01 Any help? |