PHP - Big Function, Arrays, Variables...i Want To Speed Things Up.
Okay I have a function that stores data into an Array. The function takes about 7 seconds to run and through a number of different loops it creates one final array with about 15,000 keys. I want to recall this data a number of times in different functions, however how can I have this data easily accessible without running the function each time.
EX: Code: [Select] function theFunction() { for($x=0;$x,=15000;$x++) { //Run the loop and store data. $string[$x] = //output from other loops and calculations } return $string } //Then later on if I want to recall the data the only way I know how is to do the follow: $newstring = theFunction() The only problem I have with this is that it has to re-run the function every time in order to get to the data it spits out. How can I store this data into another array outside of the function without having to re-run it? I hope this makes sense. Thanks. Similar TutorialsHi, Which one is better from performance view (CPU usage and etc)? using too many Variables or a single Associative Array or generally an Array? This one: $ld_linkdump_title = get_option('ld_linkdump_title'); $ld_linkdump_widget_title = get_option('ld_linkdump_widget_title'); $nw_option = get_option('ld_open_nw'); $ld_open_branding = get_option('ld_open_branding'); $ld_stylesheet_option = get_option('ld_stylesheet'); $ld_number_of_links = get_option('ld_number_of_links'); $ld_number_of_links_widget = get_option('ld_number_of_links_widget'); $ld_number_of_rss_links = get_option('ld_number_of_rss_links'); $ld_number_of_links_be = get_option('ld_number_of_links_be'); $ld_repeated_link = get_option('ld_repeated_link'); $ld_linkdump_fd = get_option('ld_linkdump_fd'); $ld_linkdump_rss_desc = get_option('ld_linkdump_rss_desc'); $ld_branding_bg = get_option('ld_branding_bg'); $ld_archive_days = get_option('ld_archive_days'); $ld_archive_pid = get_option('ld_archive_pid'); $ld_show_counter = get_option('ld_show_counter'); $ld_show_description = get_option('ld_show_description'); $ld_show_description_w = get_option('ld_show_description_w'); $ld_send_notification = get_option('ld_send_notification'); $ld_auto_approve = get_option('ld_auto_approve'); $ld_short_url = get_option('ld_short_url'); or this: $options['ld_linkdump_title'] = get_option('ld_linkdump_title'); $options['ld_linkdump_widget_title'] = get_option('ld_linkdump_widget_title'); $options['nw_option'] = get_option('ld_open_nw'); . . . Howdy, I used to have a whole bunch of terms (PreK, Elem, MS, HS etc...) together into a single variable called "levels". They terms were separated by commas. The following code created a pulldown menu that allowed me to "filter" the page for any one particular term. Worked terrific... Code: [Select] <? //remove any old level from query $tmp = array(); foreach ($_GET as $fld => $val) if ($fld != 'levels') $tmp[] = $fld . '=' . $val; $page_name = $_SERVER['SCRIPT_NAME'] . '?' . implode('&',$tmp); ?> <?php echo ' <form name="form4" action="" method="get" class="tight"> <select name="levels" >'; ?> <option <?php if(empty($_GET['levels'])){ echo "selected=\"selected\""; } ?> value="<?php echo "$page_name" ?>">DISPLAY ALL LEVELS</option> <?php if ($_GET[levels] == 'PreK') { echo '<option selected value="'; ?> <?php echo "$page_name" ?> <?php echo '&start=0&levels=PreK">PreK</option>'; } else { echo '<option value="'; ?> <?php echo "$page_name" ?> <?php echo '&levels=PreK">PreK</option>'; } if ($_GET[levels] == 'Elem') { echo '<option selected value="'; ?> <?php echo "$page_name" ?> <?php echo '&start=0&levels=Elem">Elem</option>'; } else { echo '<option value="'; ?> <?php echo "$page_name" ?> <?php echo '&levels=Elem">Elem</option>'; } if ($_GET[levels] == 'MS') { echo '<option selected value="'; ?> <?php echo "$page_name" ?> <?php echo '&start=0&levels=MS">MS</option>'; } else { echo '<option value="'; ?> <?php echo "$page_name" ?> <?php echo '&levels=MS">MS</option>'; } if ($_GET[levels] == 'HS') { echo '<option selected value="'; ?> <?php echo "$page_name" ?> <?php echo '&start=0&levels=HS">HS</option>'; } else { echo '<option value="'; ?> <?php echo "$page_name" ?> <?php echo '&levels=HS">HS</option>'; } if ($_GET[levels] == 'College') { echo '<option selected value="'; ?> <?php echo "$page_name" ?> <?php echo '&start=0&levels=College">College</option>'; } else { echo '<option value="'; ?> <?php echo "$page_name" ?> <?php echo '&levels=College">College</option>'; } if ($_GET[levels] == 'Prvt') { echo '<option selected value="'; ?> <?php echo "$page_name" ?> <?php echo '&start=0&levels=Prvt">Prvt</option>'; } else { echo '<option value="'; ?> <?php echo "$page_name" ?> <?php echo '&levels=Prvt">Prvt</option>'; } if ($_GET[levels] == 'Admin') { echo '<option selected value="'; ?> <?php echo "$page_name" ?> <?php echo '&start=0&levels=Admin">Admin</option>'; } else { echo '<option value="'; ?> <?php echo "$page_name" ?> <?php echo '&levels=Admin">Admin</option>'; } echo ' </select> </form>'; ?> Now, I'm keeping all those terms as separate variables, and combining them in an array. (I think that's right.) Code: [Select] $PreK = $PreK; $Elem = $Elem; $MS = $MS; $HS = $HS; $College = $College; $Admin = $Admin; $Prvt = $Prvt; $levels = array($PreK, $Elem, $MS, $HS, $College, $Admin, $Prvt); foreach ($levels as $key => $v ) if (!$v) unset ($levels[$key]); $levels = implode(', ', $levels); echo $levels; My question, how do I modify my pulldown form (above) to check the WHOLE array for these values? I'm so lost... Thanks. ~Wayne Hi I have a page that the user selects a category and I have the page sending a variable to a page. However, I want the user to be able to select multiple options and therefore need the page doing the query to build an array and change the search results accordingly! Please can someonehelp me with what I have as I am jsut NOT getting my head around this! Here is the 'form' info Code: [Select] <input name="jqdemo" value="6" type="checkbox" id="party"/> <label for="party"></label> <a class="checkbox-select" href="# id="6" onclick="showUser(this.id)""><img src="Assets/images/blank.png" alt="" width="120" height="180" /></a> <a class="checkbox-deselect" href="#" id="0" onclick="showUser(this.id)"><img src="Assets/images/blank.png" alt="" width="120" height="180" /></a> Then this is the page that is doing the query Code: [Select] <?php $q=$_GET["q"]; $con = mysql_connect('localhost', 'root', ''); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("db_pyf", $con); //$sql="SELECT * FROM tbl_product WHERE cat_id IN '".$q."'"; $sql="SELECT * FROM tbl_product WHERE cat_id IN (3,1,2)"; $result = mysql_query($sql); echo "<table border='1'> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> <th>Hometown</th> <th>Job</th> </tr>"; while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['prod_name'] . "</td>"; echo "<td>" . $row['prod_desc1'] . "</td>"; echo "<td>" . $row['member_id'] . "</td>"; echo "<td>" . $row['cat_id'] . "</td>"; echo "<td>" . $row['cat_id'] . "</td>"; echo "</tr>"; } echo "</table>"; mysql_close($con); ?> But, as I have said, I want the user to be able to select multiple options and want the search to adjust accordingly! Hello, I am a PHP biginner. I would be grateful if you could help with the issue below. I have created three input dynamic variables in a separate php file using a For lopp.
<?php
The form works well. In another PHP I would like to use the three arrays workday[], startTime[] and endTime to calculate the duration between startTime and endTime for each working day. I can access the different arrays using Foreach like below but I don't see how to combine thos arrays in order to be able to calculate the duration between two data that are in diffrent arrays. Is it possible to make calculations using variables stored in different arrays ? If so could you help me understand how ?
<?php
if (isset($_POST['workday'])) { echo $workday . "<br>;
}
echo $startTime. "<br>;
if (isset($_POST['endTime'])) {
echo $endTime. "<br>;
I have the following loop in which I receive Parse error: $letters = array ("A", "B", "C", "D","E", "F", "G", "H","I", "J", "K", "L", "M", "N", "O", "P","Q", "R", "S", "T","U", "V", "W", "X", "Y", "Z", "Æ", "Ø", "Å"); for ($i = 1; $i < 29; $i++) { if ($_POST['$letters['$i']']){ echo "You have selected the following products:" . "<br>" . $_POST['$letters['$i']]; } } or is it possible to write something like that: for ($i = 1; $i < 300; $i++) { if ($_POST['$i']){ echo "You have selected the following products:" . "<br>" . $_POST['$i']; } } Please, help me. I need to use array and variables inside _POST[]. Hello, I've created a function whereby I want to return the school_id associated with a particular user. Each user will be associated with exactly one school. My query below works, but the thing that it returns is an array; I need to make use of it as a variable (say $instructor_school_id). Any idea how to make the conversion from a single element array into a non-array variable? Thank you.... function getInstructorSchool($read, $user_id) { $sql = "SELECT school_id FROM users WHERE user_id = $user_id"; return $read->fetchRow($sql); } Hi I have a function that takes a postcode and splits it so i can enter into DB into two formats, full postcode and prefix. The function is: function check_form_postcode($postcode) { $postcode = strtoupper(str_replace(chr(32),'',$postcode)); $suffix = substr($postcode,-3,3); $prefix = substr($postcode,0,(strlen($postcode)-3)); if (preg_match('/(^[A-Z]{1,2}[0-9]{1,2}|^[A-Z]{1,2}[0-9]{1}[A-Z]{1})$/',$prefix) && preg_match('/^[0-9]{1}[ABD-HJLNP-UW-Z]{2}$/',$suffix)) { $postcode_syntax_check = 1; } else { $postcode_syntax_check = 0; } if($postcode_syntax_check){ $return = $prefix."::".$suffix; } return($return); } I POST the form data and in the top of the same page I get all of the form data and here is is where things go wrong: if ($b == 'go') { //Gets form data $main_event_name = my_import('main_event_name', 'P', 'TXT'); $main_event_type = my_import('main_event_type', 'P', 'TXT'); $main_event_date = my_import('main_event_date', 'P', 'TXT'); $main_event_city = my_import('main_event_city', 'P', 'TXT'); $postcode = my_import('postcode', 'P', 'TXT'); $main_event_added = my_import('main_event_added', 'P', 'INT'); $main_event_active = my_import('main_event_active', 'P', 'INT'); $postcode_array = check_form_postcode($postcode); $postcode = explode($postcode_array, "::"); $prefix = $postcode[0]; $fullpostcode = $postcode[0]." ".$postcode[1]; $valkey = md5(microtime()); $info = array( "main_event_name"=> $main_event_name, "main_event_type" => $main_event_type, "main_event_date" => $main_event_date, "main_event_city" => $main_event_city, "main_event_active" => $main_event_active, "main_event_added" => $sys['now'], "main_event_pcode" => $fullpostcode, "main_event_pcode_prefix" => $prefix, "eo_id" => $eo['id'] ); $table = $db['main_event']; $userid = my_insert($info, $table); When I enter into the DB all I get is the "::" no data. I know that the POST works as I can enter the data easily without the function going wrong. Thanks for any help, i am new to arrays go easy if I have made an obvious mistake! Cheers... I would like to be able to use a succession of php preg_match() and preg_replace() functions in one script without having to produce clutter in this match and replace php coding script and without its results showing arrayed forms. The following is a RegExp formula that I'm comfortable with that involves only a replace function. I'm curious what the best way would be to scoot a RegExp match function into a script like this one that is consistent with the same $current .= preg_replace('/a/', 'b', $current); php code that I've shown here et. al. that can be written out on one string. I've seen some php implode() functions, but my concern is that an additional function as such along with preg_mach() functions will cause a lot of deviation in a list of regular regex match and replace functions. What can I do to keep both php match and replace RegExp functions strings typed out in linear concession for the sake of keeping things organized when strictly relating to regex functions and working with them within php and working something like an implode() function into my php script so that match and replace functions can produced organized results outside of having to make use of arrays? <?php $file = 'sample.txt'; $current = file_get_contents($file); $current .= preg_replace('/a/', 'b', $current); file_put_contents($file, $current); ?> Edited May 6, 2020 by mojobadshah Hello, I am trying to define some variables in a function, but the variable just returns null no matter what I do. Could someone please tell me what I'm doing wrong? Code: [Select] <?php function checkname() { global $t; if($_SESSION['name'] == '') { return false; $t = false; } elseif(isset($_POST['cont']) && $_SESSION['name'] != '') { return true; $t = true; } } var_dump($t); // returns NULL upon correct or incorrect submit. ?> I have a script that uses two functions and a simple switch statement. If I wanted to take the value of variables from function 1 and use them in function 2, would I have to declare them global in both functions, function 1, function 2, or outside the functions? For example Code: [Select] <?php function function_1() { //Here? global $variable_1; $variable_1 = hello world; return $variable_1 } function function_2() { //Or Here? global $variable_1; echo $variable_1 } //Or here? global $variable_1 //Or in all three places? I want the variable to be available everywhere in the script! ?> Hello I have a table with four variables. By choosing each of the variables we obtain a numerical value. I have a form with each of the variables to be selected and what I meant was that it appeared the value without having to place the table on page. step I (VAR 1) VAR2 VAR3 8h 10h 12h 14h 16h 18h(VAR4) A 0-30 4 2 1 1 2 4 A >30 1 3 2 4 5 3 B 0-30 7 6 4 6 4 3 B >30 4 5 3 6 3 5 C 0-30 2 2 2 2 1 8 C >30 8 8 5 6 2 2 D 0-30 6 9 8 2 8 8 D >30 5 5 6 8 6 8 step II (VAR1) VAR2 VAR3 8h 10h 12h 14h 16h 18h(VAR4) A >30 2 3 5 8 2 6 B >30 2 8 2 9 8 8 C >30 8 9 2 8 5 2 D >30 8 2 1 8 2 9 step I and step II is the first variable, then we have to see if it was A, B or C (second variable) and perhaps more complicated if the input value is between 0 - 30 or >30 (third variable) in stage I or greater than zero (third variable) in step II. The four variable was the hours. Have any suggestions on how I do this? Thanks I have a php script. I defined a variable outside of a function, but i cannot echo the variable inside the function. When I execute this: <?PHP $testvar = "test worked!"; testfunction(); function testfunction(){ echo $testvar; } ?> Nothing happens. what am i doing wrong. I did this on my local host. Apache running on Windows Vista Ultimate 32 bit Edition. Thanks in advance.
I have a php file with a bunch of variables declared. I now need a function to put data on a separate page that pulls variables from the required page. <?php function getplayer($position) { // start function //$new_position = "$" . $position; $new_position = $position; $file = "their.php"; require "$file"; //echo $qb1; this displays the name John Doe...as $qb1 is declared in the required file $db_select_their = "bschultz_their"; $servername = "localhost"; $username = "user"; $password = "pass"; $dbname = "db_name"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM (select number as position_number, name as position_name, pronunciation as position_pronunciation, pos as position_pos, height as position_height, weight as position_weight, year as position_year, city as position_city, state as position_state, notes as position_notes FROM $db_select_their WHERE name = '$new_position') as position"; //$sql = "SELECT * FROM bschultz_their WHERE name = $new_position"; echo $sql; //exit; /* this displays this text... SELECT * FROM (select number as position_number, name as position_name, pronunciation as position_pronunciation, pos as position_pos, height as position_height, weight as position_weight, year as position_year, city as position_city, state as position_state, notes as position_notes FROM bschultz_their WHERE name = '') as position The name is empty */ $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "#: " . $position_number . " - Name: " . $position_name . ""; } } else { echo "0 results"; } } // end function getplayer("${$qb1}"); $conn->close(); ?>Edited September 8, 2019 by bschultz Hello I've have read that global variables should not be used. so if i have 2 .php files: index.php - main content php file sitefunctions.php - php functions site file on my index.php page i have the following (an example of my problem): <?php displayError($errorID); ?> and in the sitefunctions.php file i have the following (an example of my problem): <?php function displayError($errorID) { if($errorID == 1) { echo "Password Failure"; } else { echo "Other Failure"; } } ?> now that works but since when first accesing that page the $errorID is not set then i get an error. How can i achieve this without first setting a blank $errorID global variable? Thanks Hello everyone, Can someone show me a way how to pass $_post variable from a form to a function? So, input username and input password to a function login($username, $password). Hello, my global variable is getting whacked (defined null or being undefined) after a function call. I'm not sure if it's happening when leaving the function that assigns it or when the form is "posted", or something else. Code: [Select] <? //global variables $globalVarString = ""; //function definitions function displayResults() { global $globalVarString; if ($globalVarString == "") {displayForm("please enter your search string again");} else {displayForm("you typed: $globalVarString");} } function getResults($searchInput) { global $globalVarString; $globalVarString = $searchInput; //give status ?> <html><head><title>Search</title></head><body> <form action="<?=$_SERVER['PHP_SELF']?>" method="post"> Thanks for entering your data (<? echo "$globalVarString" ?>).<br><br>Please press the submit button to process your data    <input type="Submit" value="Submit" name="processQuery"> </form></body></html> <? } function displayForm($message) { //prompt for input ?> <html><head><title>Search</title></head><body> <form action=" <? $_SERVER['PHP_SELF'] ?>" method="post"> <h3>Please enter your search <input type="text" name="searchString">    <script type="text/javascript">document.forms[0].searchString.focus();</script> <input type="Submit" value="Submit Query" name="searchQuery"></h3> </form> <? if (!$message == ""){echo "<br>    <h4>" . $message . "</h4><br>";} ?> </body></html> <? } //main() if(array_key_exists('searchQuery', $_POST)) {getResults($_POST['searchString']);} elseif (array_key_exists('processQuery', $_POST)) {displayResults();} else {displayForm("");} ?> I have the array defined and print_r (outside the function is show what I need...) However, I need to somewhay pass those three arguments - name, price, shipping (keys & values) into the "all_products" function and assign (inside the function) each element to a variable {name, price, shipping}. Code: [Select] function all_products($key,$value) { # This is where I'm lost - I know the values are passed to the function but how to I assign them to below variable? echo "$name"; echo "$price"; echo "$shipping"; // Products array defined to send values into "all_products" function & loop to display item name & individual pricing (using WHILE LOOP) $products = array('Product1' => array ( 'name' => 'item one', 'price' => '30.00', 'shipping' => '0.00'), 'Product2' => array ( 'item two', 'price' => '19.50', 'shipping' => '0.10'), 'Product3' => array ( 'item three', 'price' => '21.99', 'shipping' => '0.10') ); while (list($keys, $values) = each($products)) { while (list($k, $v) = each($values)) echo "Checking Looped Data Outside Function: <strong>$k: </strong> $v<br/>"; # echo "<pre>"; # print_r($value); # echo "</pre>"; # Trying to send array elements into "all_products" function & echo (name, price, shipping) keys and values inside that function all_products($k,$v); } Hey ive been wanting to know how to make a function call another function which will then create a variable which i can send back to first function where i can use it. I tried somthing like this Code: [Select] <?php a(); function a($wall) { b(); echo $wall; } function b() { $wall = "test"; #a($wall); } ?> Thats what i tried but ofcourse didnt work, how would i go about doing this? Thanks. Hey guys, I want to pass the unique id of a node to a function when that image is clicked. Actually i am a newbee in php so don't know what to search about or where to look for it,but find this place and you all guys so helpful so i am asking for a guide here |