georegjlee Posted March 8, 2007 Share Posted March 8, 2007 I'm trying to search an array for a secified indices and then assign a value to that indices. Ive been at it all day and all I get when I display the array is the indices with no values. Any ideas? problem_array contains the value "BN BN01 2". <html> <head> <title>First PHP Script</title> </head> <?php function F_SearchArr($arr, $item1, $item2) { foreach ($arr as $element => $value) { if (strcmp($element, $item) == 0) { return ($arr[$element] = $item2); } } } //connection to the database $dbhandle = mysql_connect("localhost", "root", "") or die("Couldn't connect to SQL Server on $myServer"); //select a database to work with $selected = mysql_select_db("waterways", $dbhandle) or die("Couldn't open database myDB"); //declare the SQL statement that will query the database $query = "SELECT t1.waterway_initals, t1.waterway_id, t2.problem_severity FROM waterways=t1, pending_problems=t2 WHERE t2.waterway_id = t1.waterway_id"; //execute the SQL query and return records $result = mysql_query($query, $dbhandle); if (!$result) { echo 'Could not run query: ' . mysql_error(); exit; } ?> <h3 style = "color: blue"> Problems Table</h3> <table border = "1" cellpadding = "3" cellspacing = "2"> <?php for ( $counter = 0; $row = mysql_fetch_row($result); $counter++) { print( "<tr>"); foreach ( $row as $key => $value ) { $problem_array[] = "$value"; print ( "<td>$value</td>" ); } print ( "</tr>" ); } //close the connection mysql_close($dbhandle); $barrow_array = array( "BN01" => " ", "BN02" => " ", "BN03" => " ", "BN04" => " ", "BN05" => " ", "BN06" => " ", "BN07" => " ", "BN08" => " ", "BN09" => " ", ); //Display problem array. for ( $i = 0; $i < count( $problem_array ); $i++ ) print ( "$problem_array[$i]" ); print ( "<br />" ); for ( $i = 0; $i < count( $problem_array ); $i++ ) { switch ($problem_array[$i]){ case "BN": F_SearchArr($barrow_array, $problem_array[++$i], $problem_array[++$i]); break; } } // Display barrow array. foreach ( $barrow_array as $element => $value ) print ("$element is $value <br />" ); ?> </table> <body> </body> </html> Link to comment https://forums.phpfreaks.com/topic/41821-array-function/ Share on other sites More sharing options...
Psycho Posted March 8, 2007 Share Posted March 8, 2007 Why on earth would you want to traverse the entire array if you already know the index you are searching. Your problem though is that you are using $item in your function which has not been defined. You should have used $item1 I think. Anyway, I think this will be more efficient: function F_SearchArr($arr, $arrIdx, $replaceVal) { if (isset($arr[$arrIdx])) { $arr[$arrIdx] = $replaceVal; } return; } Link to comment https://forums.phpfreaks.com/topic/41821-array-function/#findComment-202817 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.