Arrays And Foreach
I have a multi-dimensionsal array in the form of a 6 x 10 table. I have 2 problems:
1) The foreach statement that inputs each row into a table, and
2) The php syntax in the table.
First, I'm still building, so the input is in the form of a string that I 'extract' data from. There are 7 input strings in the following form: Code:
View Complete Forum Thread with Replies
See Related Forum Messages: Follow the Links Below to View Complete Thread
Looping Through Arrays With Foreach
Foreach is a language construct, meant for looping through arrays. There are two syntaxes; the second is a minor but useful extension of the first: foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement For example: <?php $arr = array("one", "two", "three"); foreach ($arr as $value) { echo "Value: $value "; } ?> This will output: Value: one Value: two Value: three --=[ Why not to use list & each ]=-- Another method to loop through an array is the following: <?php while (list(, $value) = each($arr)) { echo "Value: $value<br /> "; } ?> This has some disadvantages: - It is less clear, because list() looks like a function but actually works the other way around: instead of returning something, it takes a parameter by being the left-hand side of the expression and assigns values to the parameters. - You have to reset() the array if you want to loop through it again. - It is approx. three times slower than foreach. --=[ About for & count ]=-- Another method to loop through an array: for ($i = 0; $i < count($arr); $i++) { echo "value: $arr[$i] "; } Consider this array: array(5 => "Five"); The above for-loop would loop from elements 0 through 5, while only one element exists. If this is what you want, the for-loop is an effective way to loop through an array. If not, use foreach instead.
Printing Arrays In A ForEach Statement?
I have the the following script which simply parses a remote file and sets the item I am looking for into an array. My question is how do I turn that array into an echo or print statement. PHP Code:
Foreach Loop Contains Arrays In Some Values
I'm looping through the keys and values of a form submission using foreach($_POST as $key => $value) echo "$key = $value<br>"; No problems there. All works as expected. But seveal of the values are arrays and the echo comes out like: subjectone = Array subjecttwo = Array There could be as many as 9 elements in each array but there may be as few as one. How can I get those $value that are arrays to echo the entire array using a foreach loop? I would like to end up with all values printed in the page whether in an array or not.
Foreach Loop With Nested Arrays
I haven't programmed in PHP in quite a while. Could anyone help me with a foreach loop in a nested array? I have a function which returns $stock (for an online pricing catalog). $stock[0] is ( [0] =Item, [1] =Sale, ...) an array of column headers. $stock[1][$i] is ([Item] =SL, [Sale] =300, ...) an array of column headers to value for item $i What I have to print the header row for the pricing table is: print("<TR>"); foreach ($stock[0] as $num =$val) { print("<TH>" + $val + "</TH>"); } print("</TR>"); I've also tried ($stock[0] as $x) print($x). What returns is five zeroes. Not in table cells, just "<TR>00000</ TR>". Does anyone have any ideas what I've done?
Accessing Multiple Arrays Using Foreach
I have been searching all afternoon for an answer to this and haven´t found a solution so my last resort is asking here I am collecting links from a few documents on our site using this: <?php $data = file_get_contents('http://www.example.com/'); preg_match_all("/out.php?url=(.+?)" target/",$data,$match); preg_match_all("/class="id" title="(.+?)"/",$data,$desc); foreach($match[1] as $url ) && foreach($desc[1] as $fulldesc){ echo urldecode($url); echo "| $fulldesc<br>"; }?> Basically , I want to output all the links and their respective descriptions separated by a pipe character. But reading from the two arrays is giving me a bit of a hard time.I now know I cannot use the && operator, I just left it in so you guys could see what I´m trying to do. How can I do this? I´m not much of a programmer but from what I have read the other option I have is using multi-dimensional arrays? I might be extracting the URL, the description and then some more data later on so this might be a better approach.
Either Foreach Or While
Ok, i need the best method of doing this. I need to use the while code or foreach code and take every part of an array, and put it into this form.... PHP Code: Name_Of_Field = Name_Of_Field_Value as in like dynamic variables, but i need to know the best way to print every value of an array. Whats your opinion on the way to do it, please include code sample.
PHP Foreach HELP!
I have this bit of code, that isn't valid, and I need some help getting it to work... Currently, I get an error because I am calling the next() function within a foreach loop. I am opening a flat file with data in the format of: 01|data1|data2 01 Being Gallery Name, data1 being the filename, data2 being photo caption. Basically I need to look at the line from the text file, and if the first 2 digits do not match the gallery I have specified, then move on to the next line, completely ignoring the first line... Code follows: <? $gallery = 03; $data = file('gallery.txt'); echo "<table border=0 width=500 align=center>"; foreach ($data as $line) { list ($g, $q, $a) = explode('|' , trim($line) ); if ( $g != $gallery ) next($line); else { echo "<td width=50% valign=top><img src='/gallery/$q' width=220><br>"; echo "$a<br>"; echo "<a href="/gallery/$q">Enlarge</a><br><br></td>"; $ee++; //2 - row if($ee%2==0) echo "<tr>"; } echo "</table>"; } ?>
Foreach Vs Each
I've read somewhere that to iterate an array, foreach($a as $k=>$v) is supposed to be less performant than while (list($k, $v) = each($a)). The reason being that the foreach construct needs to duplicate the whole array to iterate through it. I decided to try it, with an array of 1000 elements, iterating through it and just echoing the key. Each element of the array is a string of about 500 chars. What I've done is traversing the 1000 elements of the array 1000 times with each syntax. It turns out that the foreach is always faster, of about 20%. I know my test is not ISO-2001, but I wanted to run it just to see. Now i wonder why my conclusions are different from what it's supposed to be. I know I don't take into account memory usage, as it is supposed to be a drawback of using foreach, but as for speed it seems to be faster. In fact I run this test to see if really it was faster, in which case I would always use the each syntax in my scripts from now on (I always use foreach: it seems more natural to me, and I did not know of the supposed performance flaw) . Now I find myself confused. What do you use to traverse arrays, and for what reasons? Any recommendations? Thanks
Foreach
I'm trying to turn each $_POST into a variable so that I can later assign it a value. Not sure how this can be done.
Arrays Within Arrays, How To Split
I have been stumped on this one and it is probably easier than I think it is, especially since my brain is fried. This is what my array looks like: array(7) { ["injuredPerson"]=> string(0) "" ["dates"]=> string(0) "" ["describe"]=> string(0) "" ["location"]=> string(0) "" ["type"]=> array(3) { [0]=> string(8) "abrasion" [1]=> string(10) "amputation" [2]=> string(12) "asphyxiation" } ["part"]=> string(0) "" ["times"]=> string(0) "" } This is actually an array of information from a form check. I have the error handling check the form and depending on if there is an error or not, the array gets populated with "" or an actual value(s). I am testing a checkbox area of the form (the name is type, so type can hold an array of values, thats why it currently contains abrasion, amputation, and asphyxiation). I have had no problem going through the array until I get to the area with an array within the array. Let me give you some code so you can see how I am doing this:
Searching Arrays With Arrays
ive looked through alot of the array search functions and i dont think any of them support arrays as the "needle" to search for. so say i had a numeric array, $array1 with say 5 elements, 0-4, each element is a single word, lowercase. say i had another numeric array structured the same way called $array2 with say about 5 elements, 0-4. Is there a function which i could use or does anyone know of an easy way to search every element in $array1 and compair it through each of the elements of $array2? and if a duplicate is found in $array2 have that element be removed or unset? im sure this can be done probably easy with some kind of loop function, but thats my weak point right now in php and im working on it.
Foreach Post
I'm not asking for help, im posting help. if anyone wants to use foreach to return post vars, here's the code: <? if($_POST['Submit']) { echo "yay"; foreach( $_POST as $post ) { echo $post." = ".$_POST[$post]; } } ?>
Foreach() Problem
When trying to do a statement like the following: $filename = "/file/path/to/sites.inc"; $file = fopen ($filename, "r"); $fcontents = fread ($file, filesize ($filename)); fclose ($file); foreach($fcontents AS $line) { echo "$line "; } I get the following error message: Fatal error: Call to unsupported or undefined function foreach() Why is this happening? I'm used to perl and I know perl don't do weird stuff like this. I checked the value of fcontents and it does contain the information from the file but still no dice.
Foreach Question
I am wanting to compare two things: the information from the $_POST and my existing data in $olddata -> this is an array obviously. I always forget how to use this foreach inside one another. I want to check $_POST['fname'] against $olddata['fname'] and if they are the same, for simple testing I want to print out SAME and if different, DIFFERENT. foreach ($_POST as $nkey => $new){ foreach($olddata as $okey => $old) { if ($new == $old) { print '"'.$new.'" AND "'.$old.'" are the <b style="color:red">SAME</b>; Next... <br />' } else { print '"'.$new.'" AND "'.$old.'" are the <b>DIFFERENT</b>; Next... <br />' } } }
Foreach() From A Database?
Hi, I am making a script to insert data into a database (via a html form). But instead of me making a form with about 30 fields (cos thats so boring), i tried making a foreach loop that would print out a field for each field in the DB, but it didnt work! Heres the script, can anyone tell me where i went wrong? <?php require ("config.php"); // create loop $Query = "SELECT * from $TableName"; // set query to get everything from the db $Result = mysql_db_query ($DBName, $Query, $Link); print ("<form action="HandleForm.php" method=POST>"); while ($Row = mysql_fetch_array ($Result)) { // begin for each loop foreach($Row as $value) { print ("$value <textarea name="Array[$value]" rows=5 cols=40></textarea><br>"); } } mysql_close ($Link); print ("<input type=SUBMIT name="SUBMIT" value="Submit!"></form>"); ?>
Foreach Problem
The following script was running on a OS X machine running Apache 1.x and PHP 4.x. I just moved the script over to a Linux machine running Apache 2.0.51 and PHP 4.3.8, and now the foreach line does not work. It says Warning: Invalid argument supplied for foreach() in /var/www/localhost/htdocs/warehouse/whse_order_submit.php on line 39 Here is the script: <?php //get the variables from the other page $id=$_POST['id_no']; $sku=$_POST['sku']; $description=$_POST['description']; $order=($_POST['order_qty']); $store=$_POST['store']; $comment=$_POST['comment']; $ip=$REMOTE_ADDR; //check if store is empty if(empty($store)) { die("Store is required. Please press the back button and enter in your store."); } //connect to the database require('../inc/database_conn.php'); //$month=getdate(mon); //$day=getdate(mday); //$year=getdate(year); //$today=$year . "-" . $month . "-" . $day $today=date('Y-m-d'); // create the unique order number $headerqry = "INSERT INTO misc_order_header (order_date, store, comment, ip) VALUES ('$today', '$store', '$comment', '$ip')"; mysql_query($headerqry, $conn) or die(mysql_error()); $order_no=mysql_insert_id(); foreach($order_qty as $id_no => $val) { if($order_qty[$id_no] > 0) { $detailqry = "INSERT INTO misc_order_detail (order_no, id_no, sku, order_qty, order_date, store) VALUES ('$order_no', '$id_no', '$sku', '".$order_qty[$id_no]."', '$today', '$store')"; mysql_query($detailqry, $conn) or die(mysql_error() . "<BR>" . $detailqry); } }
Reverse Foreach
i have a complex multi-demensional array, where it doesnt seem that array_reverse or array_flip will reverse its order while keeping the keys matched up to the values. so one of the other possible solutions i am thinking is to see if there is a way to do foreach() on an array but have it start at the end of the array and go backwards, instead of the beginning to the front.
Foreach() Question
I've been trying for 2 days now to solve this problem, which should be pretty simple, but it is turning off to not be as simple. I am trying to pull data out from a form that was POSTed on a previous page. The code that I have that works is below: <?php for ($i = 2; $i <= $stoped; $i++) { echo'<tr>' .'<td>Step '."$i".'</td>' .'<td>Input X</td>' .'</tr>' ; } What I need to do is replace "Input X" with $step1, $step 2, ect.. until $stoped is reached. Before this code I added lines such $step2 = $_POST["step2"] ; $step3 = $_POST["step3"] ; $step4 = $_POST["step4"] ; to try to isolate the problem. I would perfer to be able to put $_POST["step2"] directly in the for loop. All of my tries though ened up with me just printing the line and not pulling the data from the form. I was also looking at foreach() and thought this might be what I am looking for. Something that will loop through the $_POST array. However what I have tried so far has not worked.
Foreach() Statement
I've got this mysql query $result_check=mysql_query("select qaid from quiz_input where quiz_input.fuid=$REGuid"); what I'm trying to do is to place qaid into an array, no problem. if (mysql_num_rows($result_check)>1) { while(list($DBqaid)=mysql_fetch_row($result_check)) $DBqaids[]=$DBqaid; } But the thing is I have a foreach() statement and the program bombs out because I have nothing in the $DBqaids array for instance. #DO I NEED SOME STATEMENT HERE?? foreach ($DBqaids as $DBqaid1) { if ($DBqaid1==$DBqaid) echo ' checked'} How do I acheive is something is in the array or not?? some sort of IF statement perhaps?
Nested Foreach
foreach($test as $var1){ foreach($test2 as $var2) { echo '"var1: " . $var1[1] . "<br>"var2: " . $var2[1] . "<br> "' } } -------------------- The $tests have values just that this nested loop doesnt work i keep getting this error message Warning: Invalid argument supplied for foreach() What is the correct way to nest a foreach
Foreach Problem
My datafile is: abc 234 def 888 keyword1 ------- ------- 1234 202 want it 2345 305 want it 34567 7732 want it secondkeyword more lines I do: (somewhat psydo-code) $data = file ("mydatafile"); foreach ($data as $line) { if ( secondkeyword ) $on = 0; if ( $on == 1 ) { grab numbers in case statment; } if ( strstr ($line, "keyword1") ) $on = 1; loose keyword1 line } My question is: is there a way to do $data++; when the first keyword is seen to skip the "----- ------" line? Or do I have to brute force code around it? In AWK I would just put "getline" with the $on = 1 entry.
Foreach Question
I am wanting to compare two things: the information from the $_POST and my existing data in $olddata -> this is an array obviously. I always forget how to use this foreach inside one another. I want to check $_POST['fname'] against $olddata['fname'] and if they are the same, for simple testing I want to print out SAME and if different, DIFFERENT. foreach ($_POST as $nkey => $new){ foreach($olddata as $okey => $old) { if ($new == $old) { print '"'.$new.'" AND "'.$old.'" are the <b style="color:red">SAME</b>; Next... <br />' } else { print '"'.$new.'" AND "'.$old.'" are the <b>DIFFERENT</b>; Next... <br />' } } }
Foreach - Array
i want to modify an array in foreach loop foreach($array as $ele){ $ele = $some_random_string; } i should see here the modified $array .
Another Foreach Question
It takes an array, usually Post, and goes through looking for array keys with a set of predefined keys in a second array. If the key is present it looks to see if its empty. If it is not then its added to an array for later use. Right now its only seeing one key - fname with 'Bob'...
Serialize Or Foreach()
I'm trying to loop thru an unserialized array pulled from mysql. First I serialize the array before storing it in mysql using: PHP Code:
While, Foreach And Select
there ive trying to make a game based on php and currently ive some problems with this part of the script, i've tryed to fix it alone with out success... This is the script: <?php include("db.php"); include("debug.php"); set_time_limit(0); dbConnect("sessions"); $sqlUID = "SELECT UserID FROM Star_USER"; $UsersID = mysql_query($sqlUID) or die("Query failed"); while ($UserID = mysql_fetch_array($UsersID,MYSQL_ASSOC)) { foreach ($UserID as $UID){ $sqlSz = "SELECT Size FROM Star_USER WHERE UserID = '$UID'"; $UserSize = mysql_query($sqlSz); $OldUS = mysql_fetch_array($UserSize); $AKA=$OldUS[0] $UpdateSTR = mysql_query("UPDATE Star_USER SET NW='$AKA' WHERE UserID='$UID'"); } } ?> What i wanted is that each time i run the script it will update the NW field in the database based on the size of the player and this for each one of them. It all works if i take the select statment from inside the foreach, but i need him there soo i can have the size of the player.
Nested ForEach?
Is it possible to nest a foreach loop inside another? If so is this done properly then: Code:
Foreach Query
i'm writting this function that takes a text and separate it by blank space and then check to see if that word is in the data base if it is, it echos out the word that is in the database if is not it echos out the original entered word. the problme is if it does not find the word in the data base it echos out Code:
Foreach() Error
i'm trying to do some simple form field validation and i keep getting the following error: Warning: Invalid argument supplied for foreach() I'm not sure what the problem is, but if anyone can help, i'd appreciate it. The following is where the error is happening. I can post all of it if needed. foreach($loler as $key => $value){ $string .= $value." "; }
PHP 4.3.10 - Mmcache 2.4.6 - Foreach()
I am having a problem when updating php from 4.3.9 to 4.3.10. Some scripts encoded with mmcache fail, particularly foreach() function . Looking for information I could read that it must to downgrade of this function from php 5, and the solution that very many forums and sites give in is to update the Zend Optimizer to version 2.5.7 (so it can load encoded scripts correctly), but after trying a lot, it does not work.
Array_walk Or Foreach??
The first php script asks the user to input the proper username and password, and select the course file they want to work with from a selection box (drop down). The second php script receives the information and checks to see if the username and password are correct and if they are, it will proceed to echo out the information contained in the selected file in a table. The format of information within a file is like this: studentnumber,lastname,firstname,coursename,email So they're delimited by the comma. Each file contains a varying amount of lines. I have to split the information into a table with each piece of information in their own cell in the appropriate row. It's required that I use file();, trim();, and split(); however, when I try to use trim or split, I get this notice of an array to string conversion and I don't know how to go around it. $resultfile = $_GET["filename"]; if (!($_GET["filename"])) { die ("Please select a course file to work with."); } else { $file = file("./courses/".$resultfile); foreach ($file as $newPiece) { $newStr = trim($newPiece); $newLine = split(",",$newStr); }} I read that array_walk loops through an array and can perform functions on each element of the array, but I'm not quite sure how to go about it. So...how would you go about it for either foreach or array_walk?
Ending Foreach Before It's Run Through All The Values
I've got a tiny question: Is it possible to end a foreach loop before it actually passed through all values ??? e.g. I got an internal counter in a foreach loop. now if the counter hits a defined number, the foreach loop shall end. I know this is possible by exiting the script, but I just need the loop to end. the rest of the code past that loop must be parsed as well.
Help With If/Else Statement Inside Foreach()
I have the code below that collects data from an array that may go to many levels. This code works well and does exactly what I want. This part of the code also formats the data to html (I removed the formating to make the post easier to read). PHP Code:
Using Str_replace In Foreach Loop
I'm trying to set up a php script to handle input from a form. One thing I want to do is to replace any semicolons that were entered with commas. I have str_replace working to do it like so: $question1 = str_replace(";", ",", $question1); $question2 = str_replace(";", ",", $question2); And it works. But since I have a lot of fields, I thought it would be more efficient to parse them with a foreach loop. But that's where I'm having a problem. I tried this but it doesn't work: foreach ($_POST as $k=>$v) { $_POST[$k] = str_replace('', ',', $v); $_POST[$k] = $v; } Can anyone show me what I need to do to get this foreach loop working properly?
Foreach Element In $_POST?
Is there a way to go through each element in the $_POST supervariable? I'm making a page with dynamic forms, so I don't know for sure how many $_POST variables there will be (the number of textboxes, radio buttons, etc changes). How can I either count them or do a foreach loop to do this?
Foreach() Only Updating Last Record?
I'm calling records on a date basis and want to prioritize them so i can list them in order of importance but it's only updating the very last record? Code:
Limit And Foreach Loop
like you can limit results with for and while loops but how do i display , say 9 out of 15 results. when i have to use foreach loop?
Foreach Is Returning Value Of First Key For All Keys
I'm having trouble with the foreach function. I'm using it twice inside a user defined function with two different arrays, and in the second instance it's returning the value of the first key for all the keys. My code is shown below and the problem areas are marked with comments. In case you're wondering, this script is for generating sticky checkboxes that include an event handler. <form> <?php if (! is_array($like)) { $like = array(); } function make_checkbox_click ($name, $query, $options, $onClick) { foreach ($options as $value => $label) { printf('<label><input type="checkbox" name="%s[]" value="%s" ', $name, $value); # This is the instance of foreach that's not working correctly. # It's returning the value of the first key for all the keys. foreach ($onClick as $key => $event) { printf ('onClick="%s" ', $event); } if (in_array($value, $query)) { echo "checked "; } echo "/> $label</label><br /> "; } } # End of user defined function. $characteristics = array( 'personality' => ' I love their personalities.', 'minds' => ' I admire their minds.', ); # This is the array that foreach isn't working correctly with. $charClick = array ( 'personality' => "alert('Aren't they the greatest?');", 'minds' => "alert('They're smarter than most people their age.');", ); make_checkbox_click (posPoints, $posPoints, $characteristics, $charClick); ?> </form>
Performance Test: For + Foreach
Ever since reading an interesting article in Linux Format on PHP whereby suggested code writing was made that could enhance performance on a server, I've started testing various bits of code everytime I found more than one method to perform a single task. I timed each method to find which would complete faster. I thought I'd share my most recent results which (I believe) should help those write their programs to be more clean/environmentally friendly on systems resources. If you don't want to read further, basically, I created two identical tasks except one used a "for" loop and the other used "foreach" loop. I found "for" loops are almost ten percent faster to use when compared to "foreach" loops when working on arrays. My problem (or task pending which way you want to look at it): I had a problem whereby I had a string that I wanted to cut to x number of words - I wanted the cut to be clean (thus not cut in the middle of a word, but cut between words)... My solution was to convert the string in to an array, take each array element (a single word) and append it to a new string - then check the length of the new string and make sure it had not exceeded maximum length. Maximum length was dynamic because sometimes I wanted the first ten (whole) words - sometimes more... While reading the temporary array (that contained the words), I knew I could perform a foreach($tmpArray as $wordCount=>$aWord) or I could perform a "for" loop that incremented a numeric variable to the maximum number of elements in the array of words. Call me sad - but I then wondered if using foreach on an array was lighter/heavier on the system then using a for loop... so I put both of them to the test. My test script below records the speed of which would complete first - a for loop, or a foreach loop when both were required to perform the same routine inside the loop... I discovered that using a for loop is about ten percent faster than using a foreach loop. A foreach loop took 45seconds on my server to perform the same test that took 42seconds using a for loop... It might not be much, but every little bit helps, especially if you have several users on your system at the same time drawing on resources used by PHP. I'm interested in any comments anyone has to offer on this...
Why Does Foreach Display Each Loop Twice
//this loop doesnt work as intended, each row displays twice, once with a number as $key and again with key name as $key!? Any ideas why? $result = mysql_query("SELECT * FROM tbl WHERE id = Ƈ' "); while($row = mysql_fetch_array($result)) { foreach ($row as $key =$value) { echo "<tr><td style='width:150px'>$key</td><td>$value</td></tr>"; }
Php Foreach Dir List Files In Dir
I've got some code to loop through a directory and it's sub directories and bring back a list of files and folders. What im wanting to do is have this in a state where i can put all info into a database so i can quickly index and then see what files are in what folders. It's all my security camera triggerd avi files. The following code will loop through an give me an array of files and folders Code:
Foreach On Checkbox Array
I am having a bit of an issue getting a foreach statement i have made to work , essentially what this for each statement is suposed to do is write a row to a database for each one of the check boxes selected here is the code:
MySQL Array/foreach
I have table with about 20 fields in it. I want to be able to dynamically pull the data for a certain record and create an array with the keys as the fields names and of course the data as the value. Here's what I have so far (and it's not working ): function get_data($record_id) { $query = mysql_query("SELECT * FROM table where record_id = '$record_id'") or die(mysql_error()); while($row = mysql_fetch_array($query )) { foreach ($row as $key => $value) { $data .= "&$key=$value"; } } return $data; } Now I want to be able to call the function and work with the data I'm trying to call. $record_id = 'xxxxxxxxx'; $test = get_data($record_id); $name = $test['username']; //This would be the username field from the table echo $name; All I get is a blank screen when I run this and I know the problem is in the foreach statement I tried to write.
Domain Ban List (foreach)
I've been working on a multimedia web site for a while and one feature that I'd like to add is the ability to "ban" specific domains. Code:
|