PHP - Function Call In Foreach()
I've made this code for a very simple registration form practice:
//assign form variables $firstname = $_POST['firstname']; $lastname = $_POST['lastname']; $username = $_POST['username']; function clean_names($dirty_name) { strip_tags($dirty_name); str_replace(' ', '', $dirty_name); ucfirst(strtolower($dirty_name)); //return $dirty_name; } $names = array($firstname, $lastname, $username); if(isset($_POST['register_button'])) { // WHY IS THIS FUNC CALL NOT WORKING?? foreach($names as $name) { clean_names($name); } echo "First Name: " . $firstname . "<br>"; echo "Last Name: " . $lastname . "<br>"; echo "Username: " . $username . "<br>"; }
The values are returned but they haven't been put through the clean_names function. Similar TutorialsHello, I am new to PHP and have come to a grinding halt in my project. I am attempting to dynamically generate values for Wordpress shortcodes ( [example] ). I have successfully created the shortcodes and am having trouble setting their value. When I call the function that is supposed to return the value for the shortcode, it returns empty. I can however hard code a string and have it returned to the function, thereby manually creating a value for the shortcode. However, because the shortcodes are being generated and filled dynamically, I need this function to work without specific values. I know this may sound like a Wordpress specific question, but I have a feeling it's just my lack of understanding of PHP operations. So, here is the basic layout: The name of the shortcode is generated from within a foreach loop that retrieves the name of custom fields on the post ($keyName). Code: [Select] $custom_field_keys = get_post_custom_keys(); foreach ( $custom_field_keys as $key => $keyName ) { $valuet = trim($keyName); if ( '_' == $valuet{0} ) continue; if ( get_post_meta($thePostID, $keyName, true) ) : $fieldName = get_post_meta($thePostID, $keyName, true); endif; $fieldValue = $_GET["$keyName"]; add_shortcode((string)$keyName, 'myFields'); } The add_shortcode function has two parameters ('name_of_shortcode', 'function_name'): Code: [Select] add_shortcode((string)$keyName, 'myFields'); I need the myFields function to return the value of $fieldValue from within the foreach loop. That's where the problem lies. This doesn't work: Code: [Select] function myFields() { $myString = preg_replace('/[^a-zA-Z\s]/', '', $fieldValue); return $myString; } This does work: Code: [Select] function myFields() { return 'Content to replace the shortcode'; } This code will replace [shortcode] with "Content to replace the shortcode" in the post. The ultimate goal is: when [$keyName] appears anywhere within the post, it will display the content returned by the myFields function ($fieldValue). However, it's not working. I can't seem to pass the value of $fieldValue to the myFields function and thereby return it to add_shortcode. Any help is appreciated and I am awaiting anxiously to answer any questions. Here's all the code together: Code: [Select] function myFields() { $myString = preg_replace('/[^a-zA-Z\s]/', '', $fieldValue); return $myString; } $custom_field_keys = get_post_custom_keys(); foreach ( $custom_field_keys as $key => $keyName ) { $valuet = trim($keyName); if ( '_' == $valuet{0} ) continue; if ( get_post_meta($thePostID, $keyName, true) ) : $fieldName = get_post_meta($thePostID, $keyName, true); endif; $fieldValue = $_GET["$keyName"]; add_shortcode((string)$keyName, 'yourFunction'); } This topic has been moved to Other Libraries and Frameworks. http://www.phpfreaks.com/forums/index.php?topic=319682.0 I can call the following function successfully as a single php program // Acknowledge and clear the orders function ack($client, $merchant, $id) { $docs = array('string' => $id); $params = array('merchant' => $merchant, 'documentIdentifierArray' => $docs); $result = $client->call('postDocumentDownloadAck', $params); return $result; } with $result = ack($t, $merchant,'2779540483'); successful output [documentDownloadAckProcessingStatus] => _SUCCESSFUL_ [documentID] => 2779540483 I'm trying to figure out how to call this function as an object from another program. Trying the following gives error ***Call to a member function call() on a non-object*** function postDocumentDownloadAck($t, $merchant, $id) { $this->error = null; $docs = array('string' => $this->id); $params = array('merchant' => $this->merchant, 'documentIdentifierArray' => $docs); ** I've tried the following which does nothing $result = $this->soap->call('postDocumentDownloadAck', $params); ** I've tried the following - which gives error "Call to a member function call() on a non-object" $result = $this->t->soap->call('postDocumentDownloadAck', $params); if($this->soap->fault) { $this->error = $result; return false; } return $result; } *** calling program snippet for above function $merchant= array( "merchant"=> $merchantid, "merchantName" => $merchantname, "email"=> $login, "password"=> $password); $t = new AmazonMerchantAPI($merchantid, $merchantname, $login, $password); $documentlist= $t->GetAllPendingDocumentInfo('_GET_ORDERS_DATA_'); $docid = $documentlist['MerchantDocumentInfo'][$i]['documentID']; $docs = array('string' => $docid); $ackorders = $t->postDocumentDownloadAck($t, $merchant,$docs); Any ideas of what I'm doing wrong are greatly appreciated. how would i display image without using foreach in this case ? <?php foreach($images as $image): ?> <div class="thumb"> <img src="<?php echo $image['url']; ?>">" /> <img src="<?php echo $image['thumb_url']; ?>" /> <?php endforeach; ?> Hi all, I want to call a javascript function from a php function like this: public function Buscar() { $HoraInicio = $_POST['edtHoraInicio']; $HoraFin = $_POST['edtHoraFin']; $FechaInicio = $_POST['edtFec1']; $FechaFin = $_POST['edtFec2']; $FechaMax = $FechaFin." ".$HoraFin.":00"; $FechaMin = $FechaInicio." ".$HoraInicio.":00"; $_GET["FechaMax"] = $FechaMax; $_GET["FechaMin"] = $FechaMin; echo $FechaMin; echo "<script language=javascript>alert('Hi.')</script>"; } but the function Buscar never show the alert but shows the $FechaMin I hopu u guys can help me out with this probem Thanks, Siddhartha Hi I have a table class and functions I want to call in another function but can't get it working. Some help will be very welcome. It seesm that the new table class is not working in this function if I pass the values to it, I have tested the class, it does get the post values I post to it so $_POST['id'] are being received as well as all the other $_POST's but the table class and find function is not working, it works fine if I don't put it in a function.. function edit() { if (isset($error)){ $error.="Please fix the error(s) above";} else { if ($_POST['id'] <> "") { $update =& new table($db, 'publisher'); $update->find($_POST['id']); $update->name = $_POST['name']; $update->url = $_POST['url']; $update->contact = $_POST['contact']; $update->address = $_POST['address']; $update->phone = $_POST['phone']; $update->email = $_POST['email']; $update->save(); $error = "The Publisher has been edited"; } } } ok. say i have a list with a foreach loop in it. like this: Code: [Select] echo' <ul>'; $link = Link::find_all(); foreach($link as $links){ $name = $links->name; echo' <li>'.$name.'</li>'; } echo' </ul>'; now. say that i want to put this part : Code: [Select] $link = Link::find_all(); foreach($link as $links){ $name = $links->name; into a function so i can reuse the code... like this: FUNCTION Code: [Select] function(find_li){ $link = Link::find_all(); foreach($link as $links){ $name = $links->name; } Code: [Select] echo' <ul>'; find_li(); echo' <li>'.$name.'</li>'; } echo' </ul>'; the problem is the foreach } its not inside the function so the function will not work. but it needs to be after the </li> so that i get all the results in the <li> so is there a way to put the function before the <li> and the } after the </li> I think this is the right place to post this but please move if needed as this is my first time on this site. You can also contact me through AIM: MadLittleMods@gmail.com Okay so I have a multidimensional array that is giving me an error when I put it in a function: ERROR: Warning: Invalid argument supplied for foreach().. line 123 LINE 123: foreach ( $affiliates as $affiliate ) This does work when in one file test2.php which is attached to this post... Here is my whole function: // affiliate content function start: function affiliates_content() { global $context, $settings, $options, $scripturl, $txt; foreach ( $affiliates as $affiliate ) { echo ' <table> <tr> <td> <a href="',$affiliate[href],'"><img src="',$affiliate[image],'"></a> </td> <td> ',$affiliate[title],' <br> <small><a href="',$affiliate[href],'">',$affiliate[href],'</a></small> </td> </tr> </table> <br> '; } } // affiliate content function end Here is my whole array which is located on another file (subs.php - smf) // affiliates array for affiliates page $affiliates = array( array( "title" => "aff_blah1", "image" => "http://aff_blah1.net/images/aff_blah1.png", "href" => "http://aff_blah1.net/" ), array( "title" => "aff_blah2", "image" => "http://aff_blah2.net/images/aff_blah2.png", "href" => "http://aff_blah2.net/" ), array( "title" => "aff_blah3", "image" => "http://aff_blah3.net/images/aff_blah3.png", "href" => "http://aff_blah3.net/" ), ); // affiliates array end Does anyone know how to fix this problem? Hi
I'm trying to get the layout like i want but it's not easy
I have this file
<?PHP require_once("./include/membersite_config.php"); if(!$fgmembersite->CheckLogin()) { $fgmembersite->RedirectToURL("login.php"); exit; } if(isset($_POST['submitted'])) { $fgmembersite->PesquisarPorDatas(); } ?> <div id='fg_membersite_content'> <div class="CSSTableGenerator" > //I want the result here </div> <br>I want the result of this $fgmembersite->PesquisarPorDatas(); in "//I want the result here" the r of my code, when the user use the "Pesquisar" button this fucntion is called but the result comes out of my css any help please?? Edited by alphasil, 04 December 2014 - 10:32 AM. I'm writing a program that allows users to input a stock and view a historical price chart. Code is straight out of libchart charting library. Problem is, user is supposed to enter the stock symbol from a form handler (index.php) which then passes the symbol as a variable to the charting function, which doesn't get called at all:
<? php
function index() { chart($_POST['userinput']};
} ?> .
<?php
function chart($stock)
{
$prices=getdata($stock); //returns array of prices from yahoo finance
$data=analyzer($prices); //produces metrics to be charted
graph($data); } ?> //plots the metrics, outputs .html
chart.php works on its own, as I've verified by hardcoding $argv='ibm'; in its code body. But index.php can't seem to call chart.php, as I've verified by including an echo/var_dump line in chart.php (doesn't get executed at all). It doesn't have anything to do with form handling either, as chart('ibm'); doesn't call chart.php either. I don't understand how a 6-line piece of code can be so problematic. All files are in the same folder, btw.
Thanks.
okay in modlogs.php i have a function Code: [Select] <?php function modmenu($page) { ?> <dl><dt class="<?php if ($page == 'modlogs') echo '';else echo 'ust'; ?> LEFT" style='margin-left:5px'><a href='mlogs.php'><b>User Logs</b></a> </dt><dt class="<?php if ($page == 'modlogs1') echo '';else echo 'ust'; ?> LEFT"><a href="modlogs1.php">Topic/Forum Actions</a></dt> <dd> <?php } ?> in modlogs1.php i try to echo Code: [Select] modmenu('modlogs1'); to show the menu but i get unidentified function? lol isn't functions global wtf? Is this even possible? I'm trying to call function nameGen from in the function nameGen but I just get an error saying cannot redeclare. I only want it to return $newName when it is not in the array $takenVals. can this only be done with another loop and a constant somewhere? Code: [Select] $newVarVals = array(); $takenVals = array(); $varCount = count($varArray); // contents are set else where and is fine for($i = 0 ; $i < $varCount; ++ $i) { function nameGen(&$varCount,&$takenVals){ $newName = rand(0,$varCount); if(in_array($newName,$takenVals)) { nameGen(&$varCount,&$takenVals); } else{ return $newName; } } $newName = nameGen(&$varCount,&$takenVals); $takenVals[] = $newName; $newNameToKeep = '$_'.$newName; $newVarVals[] = array('oldName' => $varArray[$i], 'newName' => $newNameToKeep); } error: Cannot redeclare nameGen() Hi im new to php Im excellent in C# more but lets not go into that I was wondering how to call this function. What am i doing wrong.. <?php if(isset($_POST['submit'])) { $startDate = strtotime($_POST['startdate']); $endDate = strtotime($_POST['enddate']); if($startDate != false && $endDate != false) { $startDate = date("y-m-d",$startDate); $endDate = date('y-m-d',$endDate); SearchForBookedRooms($startDate,$endDate); } else { echo "Please select both dates!"; } function SearchForBookedRooms($startDate,$endDate)//Calling this Function Here?? { } } ?> Im trying to assign and update table rows with a random 9 character string but am receiving the error : Fatal error: Cannot redeclare make_seed() (previously declared in ... How can I clear/reset the value before the next loop Code: [Select] else { while ($data=mysql_fetch_array($users)){ $user=$data[user]; $usersarray = array($users); foreach ($usersarray as $key => $u){ //clear pass $token = ""; srand(); //generate new password $password_length = 9; function make_seed() { list($usec, $sec) = explode(' ', microtime()); return (float) $sec + ((float) $usec * 100000); } srand(make_seed()); $alfa = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM!@#$%^&*(){}[]"; for($i = 0; $i < $password_length; $i ++) { $token .= $alfa[rand(0, strlen($alfa))]; } // insert password // setup SQL statement $SQL = " UPDATE data SET pass='$token' WHERE user='$m1' "; // execute SQL statement $makeit = mysql_db_query($userdb,"$SQL",$usercid); // check for error if (!$makeit) { echo("ERROR: " . mysql_error() . "\n$SQL\n"); } Can anyone help me complete this script I can get it working with using an implode function, but for the purpose of knowledge I want to not use it. I just want it to echo back the corresponding checkboxes, but I can't get the echoing correct, it echoes back array not the value? Code: [Select] <html> <title>What do you want on your Tombstone?</title> <body> <?php $Output_form = true; if (isset($_POST['submit'])) { if (empty($_POST['toppings'])) { echo '<b>You forgot the toppings for your Tombstone.</b>'; echo '<br>'; echo '<br>'; } else { echo '<p><b>This is what you are getting on your Tombstone: '; (array)$_POST['toppings']; echo $toppings; echo '!'; echo '</p></b>'; $Output_form = false; } } if ($Output_form) { ?> <form action="ProcessToppings.php" method="post"> <p><i><h2>What do you want on your Tombstone?</h2></i></p> <p> <input type="checkbox" name="toppings[]" value="pepperoni" /> Pepperoni<br /> <input type="checkbox" name="toppings[]" value="sausage" /> Sausage<br /> <input type="checkbox" name="toppings[]" value="mushrooms" /> Mushrooms<br /> <input type="checkbox" name="toppings[]" value="cheese" /> Cheese<br /> <input type="checkbox" name="toppings[]" value="olives" /> Olives</p> <p> <input type="submit" value="Make that Peet-Za!" name="submit" /></p> </form> <?php } ?> </body> </html> This is the error that I am getting... Quote <br /> <b>Fatal error</b>: Call to undefined function readChatOnload() in <b>C:\server\xampp\htdocs\php\chat\readChat.php</b> on line <b>18</b><br /> And this is my php file... if(isset($_POST['function'])) { $function = $_POST['function']; switch($function) { case 'readNamesOnload': readNamesOnload(); break; case 'readNamesLoop': readNamesLoop(); break; case 'readChatOnload': readChatOnload(); break; case 'readChatLoop': readChatLoop(); break; } //READ NAMES ONLOAD function readNamesOnload() { die('readNamesOnload'); } //READ NAMES LOOP function readNamesLoop() { die('readNamesLoop'); } //READ CHAT ONLOAD function readChatOnload() { die('readChatOnload'); } //READ CHAT LOOP function readChatLoop() { die('readChatLoop'); } } I don't understand why this is happening. Thanks I'd like to set my own error handler function to clear some session variables, but I do not want to completely replace php's internal error handler message reporting. Is there any way to mimic the internal error message reporting so I can define my own error handler function. function myErrorHandler(){ unset($_SESSION['var']); // HERE EXECUTE Normal PHP error message reporting } Thanks I am getting this error: Parse error: syntax error, unexpected '[', expecting ')' in C:\xampp\htdocs\Work\Store\store.php on line 154 when I run the following code: Code: [Select] function categorySearch($sql) { $res = mysqli_query($this->conn,$sql); $this->results='<table>'; while($cRow = mysqli_fetch_array($res)) { function getCategoryName($cRow[0]) $this->results .= '<tr><td style="border: thin solid #000000;">' . $this->cat_str . '</td></tr>'; } $this->results.='</table>'; return $this->results; } Line 154 refers to this line: function getCategoryName($cRow[0]) Can anyone see what the problem is? Code: [Select] <html> <center> <form method="post" action=""> <b>Email</b><br><input type="text" name="email"/><br> <b>Password</b><br><input type="password" name="password"/><br> <input type="submit" name="submit" value="Login"/><br> </form> <?php if(isset($_POST['submit'])){ echo echo_post($_POST['email']); function echo_post($postvar){ return $postvar; } } ?> </center> </html> the filename is index.php How come I get the undefined function echo_post on line 14? I know it is probably something simple but I am kind of new to this, if you could help me out that would be great |