PHP - Return Array From Function.
Hi,Dear Frnds...........................I Hope U r all fine.
I am using php.Here is the problem in the Return array from function. This is the code. Code: [Select] <?php $store = array(); $test = get_my_links(); print_r($store); function get_my_links() { $my_array = array('e','f','g'); foreach($my_array as $key=> $list) { $store[] = $list; } return $store; } ?> Suppose the array is maked dynamically. please help me..THANKS... Similar TutorialsMy tree gather function gives me multidimensional array. However i want it to be one dimensional . I was getting one dimensional earlier however i forgot how i got it. Can someone please tell me my mistake Code Code: [Select] <?php include'config.php'; function tree_gather($node) { $sql = "SELECT lchild,rchild FROM tree WHERE parent = '$node'"; $execsql = mysql_query($sql); $array = mysql_fetch_array($execsql); if(!empty($array['lchild']) || !empty($array['rchild'])) { $child[] = $array['lchild']; $child[] = $array['rchild']; $eh[] = tree_gather($array['lchild']); $child = array_merge($child, $eh); $eh1[] = tree_gather($array['rchild']); $child = array_merge($child, $eh1); } return $child; } $pair = tree_gather(1000000); echo "<pre>"; print_r($pair); echo "</pre>"; ?> Output Code: [Select] Array ( [0] => 3632873 [1] => 5951538 [2] => Array ( [0] => 8930480 [1] => 7563232 [2] => Array ( [0] => 1144744 [1] => 4386810 [2] => [3] => ) [3] => ) [3] => ) I hate array... 😞 So I had a block of code inside my photo-gallery.php script that took the path to my photos directory, and went to that directory, and then read all of the photo filenames into an array. Then in my HTML, I iterate through this array to display all of the photos for my gallery. Now I would like to move that code to an included file so multiple scripts can access it and always be working with the same array. It seems to me that I need to encapsulate my code inside a function? Then I could call my getPhotoFilesArray back to my callings cript, and use that array for whatever. I haven't coded PHP in like 4 years and I am struggling to return the entire array back to my caling script. This is what I have so far... function getPhotoFilesArray($photoPath){ $photoFiles = array(); <code to find corresponding files> $photoFiles gets populated in a loop return $photoFiles; }
Then in my calling script, I have... <?php require_once('../../../secure_outside_webroot/config.php'); require_once(WEB_ROOT . 'utilities/functions.php'); getPhotoFilesArray($photoPath); var_dump($photoFiles);
I get some error...
Notice: Undefined variable: phtoFiles in photo-gallery.php line 133 (which is my var_dump).
<br> Would appreciate help getting this to work!
Edited December 6, 2019 by SaranacLake I'm trying to return to array of letters that bruteForce finally decides upon. However, I can't seem to pass the array to librarySolve. I'm feeling dumb, any help? Code: [Select] function librarySolve($string){ $temp = $this->bruteForce($string, FALSE, 0); return $temp; } function bruteForce($string, $state, $trys){ $base = $string; $state = $state; $new_letters = array(); if($trys <= 6000){ $this->new_letters = $this->generateRandomCipher(); $string = preg_replace('/[^a-zA-Z0-9-\s]/', '', $string); for($a=0;$a<=strlen($string);$a++){ $letter = substr($string, $a, 1); $pattern = "/[A-Z]/"; if(preg_match($pattern, $letter)!=0){ $new_letter = $this->new_letters[$letter]; } else if(preg_match($pattern, $letter)==0) { $new_letter = $letter; } $decipher .= $new_letter; } $word_array = explode(" ", $decipher); $count = 0; for($a=0;$a<count($word_array);$a++){ $do = $this->checkWord($word_array[$a]); if(!empty($do)){ $count++; } } if($count>=2){ $state = TRUE; } else { $state = FALSE; } if($state==TRUE){ return $this->new_letters; } else { $trys++; $this->bruteForce($base, $state, $trys); } } } Hi, i got this function to get the wordCount that i store in a tabel: Code: [Select] function getWordCount($word) { $query = "SELECT count FROM uniqueWords WHERE word='$word'"; $data = execQuery($query); return $data; } Only it returns an array, what i want is to have it return a integer, how can i do that? let say i have a function function checkme($x) { if(strlen($x)>10) { return $x; } else { return false; } } $variable=checkme("5"); so two questions i wish to ask... 1. If i wish to get the empty string for the $variable, then is it correct to have return false there? 2. If it is true that return shall not be used twice in a function as it will somehow reduce bytes space or something like that?? thanks in advance Hi all, can you give me suggestion how to return value from function like this Code: [Select] function returnArray(){ for($i=1; $i<=3; $i++){ return $i; //how to return this as array?? } } when I code "echo" inside the function then call the function it give me output => 123 but when I code "return" inside the function, it will give output => 1 Can you suggest me how to output it as array? Hi everyone for my end of studies projects I decided to do a little e-commerce problem on the filter .. I use an ajax request at the click of the checkbox this goes to my controller which calls a method of my Model class but the concern is that .. if the array $ _POST ['brands'] has several elements then only the last one is returned to me? I thought I saw one day that if the same variable is in a url then the last value will be returned to me is for security but how can I do ... I have been there for too long .. and finally despair. . Help me please... :') request payload: brands%5B%5D=arai&brands%5B%5D=bell reply :
<- prepare var_dump ()
string (4) "arai" <- bind
var_dump () of my fetchAll () since the last value taken into account is bell then I get two items of the bell brand from my bdd but no arai ... Edited October 24, 2020 by jcb789error This is object programming right? Is there a performance issue with this? for example: $notfications = ( blah blah ) ? : ''; then if ($notificatiosn != blabla){ echo 'hey'; }or.... $notifications = function(){ do my stuff here then return 'hey'; }Which way is faster or slower? Reason I Ask this is because I've been doing some object orientated programming in javascript, and didn't know you could do it in php. I'd rather do the objective way so I don't have to use so many freaking variables above the regular way, lol. Edited by Monkuar, 22 January 2015 - 12:22 PM. This is my error: Code: [Select] Fatal error: Can't use function return value in write context in /home/a8152576/public_html/SecretSanta.html on line 41 confused about why. This is the line 41: if(isset($_POST('submit')){ this is the php of my page (without the mysql data): <?php class functions{ public static function chooseGiftee($SS){ $done = false; while($done=false){ $sqllink= mysql_connect($mysql_host,$mysql_user,$mysql_password); if(!$sqllink){ echo "Could not connect! Please Try Again"; mysql_close($sqllink); } else { $selectGiftee = "SELECT * FROM SecretSantas ORDER BY RAND() LIMIT 0,10;"; while($row=mysql_fetch_array($result)){ $results = mysql_query($selectGiftee); if(!$row['Gifter']=''){ $done=false; } else { $gifteeResults = $row['Name']; $addSS = "INSERT INTO SecretSantas (Gifter) VALUES ('" .$SS. "')"; $done=true; return $gifteeResults; } } } mysql_close($sqllink); } } } if(isset($_POST('submit')){ $echoName = functions::chooseGiftee($_POST['gifterName']); echo $echoName; } ?> This is html: <form id="form1" name="form1" method="post" action=""> <p> <label>Your Name: <input type="text" name="gifterName" id="gifterName" /> </label> <input type="submit" name="submit" id="submit" value="Submit" /> </p> <p> </p> </form> Confused about the issue, first time using functions. Thanks in advance, Brandon not sure if this is possible but i do not know how to return multiple values and read them where the call was made. Code: [Select] $string = "clause1"; func1($string); // somehow read the response and use the return values seperately. // both $string2 and $string3 Code: [Select] function func1($input) { if ($input == "clause1") { $string2= "value2"; $string3= "value6"; } if ($input == "clause2") { $string2= "value3"; $string3= "value7"; } if ($input == "clause3") { $string2= "value4"; $string3= "value8"; } if ($input == "clause4") { $string2= "value5"; $string3= "value9"; } return ($requesttype, $messagetitle); } Hello everyone, Pretty much what I am trying to do is run a query and based of the queries result, return a string - as of now it is turning up blank and cant seem to pass any strings through the function. Current function: function addNewBookmark($hash,$url,$title,$username){ Code: [Select] $query = "INSERT INTO bookmarks (hash,url,title,username) VALUES '".md5($hash)."', '".$url."', '".$title."', '".$username."')"; $result = mysql_query(query, $this->connection); $message = ''; if(mysql_affected_rows($this->connection)!=1) { $message = 'This URL already exists in the database!'; return $message; } else $message = 'The URL was shared!'; return $message; } The above code seems to run fine, just cant seem to pass a string...read that you can possibly use a __toString function? but that keeps throwing errors when I try to work with it. Thanks all! Hi, I have some strange issues with my code: Code: [Select] <?PHP session_start(); $loginid = $_SESSION["valid_id"]; // First check if we are guest or user. if (!$_SESSION["valid_email"]) { $visitor = "yes"; } else { $visitor = "no"; $email = $_SESSION['valid_email']; $userid = $_SESSION['valid_id']; } //Load Header (blue menu) require("./inc/header.php"); //Load Sub-acc (silver account menu) require("./inc/sub-group.php"); //Load nav-group (Tabs) require("./inc/nav-group.php"); //Load Config file require("./inc/config.php"); //Set & get profile ID $getid = $_GET["id"]; //check ID $result = mysql_query("SELECT * FROM profiles WHERE id=('$getid') LIMIT 1"); $row = mysql_fetch_array($result); IF (mysql_num_rows($result) != 1) { exit("Invalid ID"); } //If we are guest, do we allow anon access to the profile IF ($row["privacy"] <= 10 && $visitor = "yes") { exit("You may not view this profile as a visitor, due to the users privacy settings"); } //Let's check if we are friends ELSEIF ($visitor = "no") { $result2 = mysql_query("SELECT * FROM profiles_friends WHERE user=('$getid') AND target=('$loginid') LIMIT 1"); $row2 = mysql_fetch_array($result2); $friends = $row2["status"]; if (mysql_num_rows($result2) = 0) { $friends = "no"; } } //If we are friend, do we allow access to the profile IF ($row["privacy"] >= 9 && $friends != 1) { exit("You may not view this profile because of the privacy settings."); } $row = mysql_fetch_array($result); $memgroup = $row["group"]; IF ($row["activated"] != 1) { exit("This account is suspended and cannot be viewed."); } //Check what group member is in. $result2 = mysql_query("SELECT * FROM profiles_groups WHERE id=('$memgroup') LIMIT 1"); $row2 = mysql_fetch_array($result); ?> Alright, so the error: Fatal error: Can't use function return value in write context in C:\xampp\htdocs\prog\profile.php on line 45 Code: [Select] 42. $result2 = mysql_query("SELECT * FROM profiles_friends WHERE user=('$getid') AND target=('$loginid') LIMIT 1"); 43. $row2 = mysql_fetch_array($result2); 44. $friends = $row2["status"]; 45. if (mysql_num_rows($result2) = 0) Alright, this is one thing that bothers me, the other is: Code: [Select] //check ID $result = mysql_query("SELECT * FROM profiles WHERE id=('$getid') LIMIT 1"); $row = mysql_fetch_array($result); IF (mysql_num_rows($result) != 1) { exit("Invalid ID"); I tried to put an invalid ID, and already here the script should have died/exited before executing the parts of the code that doesn't work. I tested my code on another page and it works flawlessly, perhaps this error is just generated before it actually exists i dunno.. Any way, any help is much appreciated } I need to return a specific key from the object converted to array but it seems that it dosent work Code: [Select] $toarray = (array)$tmp; $name = array_keys($toarray,'name'); print_r($toarray); print:Array ( [id] => 9 [name] => dfd [text] => fdsf [rating] => 0 [totalv] => 0 ) and when i try to return the key Code: [Select] print_r($name); Array ( => rating [1] => totalv ) But I only need the key whit the 'name' value I am trying to write a program that sends out a newsletter but I am lost at returning an array of emails. This is what I have
<?php require("../PHPMailer/class.phpmailer.php"); include 'includes.php'; $mail = new PHPMailer; $subject = $_POST['subject']; $text = $_POST['newsletterBody']; $unsubscribe = "<br /><br /><br /><br />If you would no longer like to receive these emails, please <a href='removeemail.php'>Click Here</a> to unsubscribe."; $mail->IsSMTP(); // Set mailer to use SMTP $mail->Host = 'localhost'; // Specify main and backup server $mail->Port = '465'; $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = '****EMAIL ADDRESS****'; // SMTP username $mail->Password = '****EMAIL PASSWORD*****'; $mail->SMTPAuth = true; $mail->SMTPSecure = 'ssl'; // Enable encryption, 'ssl' also accepted $mail->From = '****EMAIL ADDRESS****'; $mail->FromName = '****NAME****'; $mail->AddAddress('****EMAIL ADDRESS****', '****NAME****'); $email = getEmail("", $DBH); foreach ($email as $newEmail) { $addEmail = $newEmail['email_addr']; $mail->AddAddress($addEmail); $DBH = null; } $mail->AddReplyTo('****EMAIL ADDRESS****', '****NAME****'); $mail->WordWrap = 50; // Set word wrap to 50 characters $mail->IsHTML(true); // Set email format to HTML $mail->Subject = $subject; $mail->Body = $text . "<br /><br /><br /> To unsubscribe to this email please <a href='www.raven-consult.com/newsletter_remove.php'>Click Here</a>"; $mail->AltBody = $text; if(!$mail->Send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; exit; } echo "Message has been sent <a href='newsletter.php'>Return back</a>"; ?>This is the portion of the includes file that you need to know. function getEmail($inId, $DBH) { if (!empty($inId)) { $blogstmt = $DBH->prepare("SELECT email_addr FROM newsletter_emails WHERE id = :userId"); $blogstmt->bindParam(":userId", $inId); $blogstmt->execute(); $postArray = $blogstmt->fetchAll(PDO::FETCH_ASSOC); } else { $blogstmt = $DBH->prepare("SELECT * FROM newsletter_emails"); $blogstmt->execute(); $postArray = array(); $results = $blogstmt->fetchAll(PDO::FETCH_ASSOC); foreach($results as $row){ $myPost = new nlEmails($row['id'], $row['email_addr'], $DBH); array_push($postArray, $myPost); } } return $postArray; $DBH = null; } class nlEmails { public $id; public $email; function __construct($inId=null, $inEmail=null, $DBH) { if(!empty($inId)) { $this->id = $inId; } if(!empty($inEmail)) { $this->email = $inEmail; } } }When I try and submit the newsletter to be sent out all I get back is this error. "Cannot use object of type nlEmails as array ......" hello. im trying to get some results from a db and all i keep getting is the word ARRAY ?? I want to get all the placeholders that relate to a page. so if pageID=1 has place holder 1, place holder 2 and place holder 3 it will return 1, 2, 3 etc... in the db i have id pageID phNumber 1 1 1 2 1 2 3 1 3 etc.. this is the code i have Code: [Select] public function find_placeholders($pageID=0){ $sql = "SELECT phNumber FROM ".self::$table_name." WHERE pages_id=".$pageID.""; $result_array = self::find_by_sql($sql); return $result_array; } and on the page i have.. Code: [Select] <?php echo Placeholders::find_placeholders($pageID); ?> all i get is Quote Array once i solve this problem i will want to use each number in the array to find the content for each. so if i get 1,2,3 i will try and do some thing like. foreach placeholder number echo elements but 1 step at a time thanks for any help rick phpfreaks I am querying a database using pdo but I keep getting an array that returns two results. As you can see from the array below it returns the id and result and then repeats the result . I only want the keys with text to be returned. Any help would be great. Code: [Select] ( [0] => Array ( [Ticket_ID] => 2 [0] => 2 [Customer_id] => 1 [1] => 1 [Business_Name] => [2] => my database method is Code: [Select] private function queryFetchAllPDO($query) { try { $this->dataObj->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sth = $this->dataObj->prepare($query); $sth->execute(); echo"I am here"; $result = $sth->fetchAll(); print_r($result); // $stmt = $this->dataObj->query($query); // $stmt->setFetchMode(); // $result = $stmt->fetchAll(); } catch (PDOException $e) { $e->getMessage(); } return $result; } and the query method is Code: [Select] private function clieViewHome() { //find user id $sql = "SELECT Customer_id FROM customer WHERE Username='" . $this->user . "'"; $sessAccess = $this->connection->getQueryFetchPDO($sql); foreach ($sessAccess as $value) { $userID = $value; } //place into query $sql = "SELECT * FROM tickets WHERE Customer_id ='" . $userID . "'"; $tableArr = $this->connection->getQueryFetchAllPDO($sql); print_r($tableArr); foreach ($tableArr as $key => $value) { $return .= "<tr>\n"; foreach ($tableArr[$key] as $value2) { $return .="<td>" . $value2 . "</td>\n"; } $return .= "</tr>\n"; } return $return; } Hello. I'm new to php and need a little help please. I try to build a class that return an Array of all the table in my db. and be able to get all the data by there col name (like username, password....) but all i got is the last record from the db. here is the class: <?php class db{ function getall($table, $search){ $sql = "SELECT ". $search ." FROM " . $table; $result = mysql_query($sql) or die('Error, insert query failed' . mysql_error()); while($row=mysql_fetch_assoc($result)){ $data = $row; } return $data; } and this is in the html page: $data = $db->getall("users", "*"); foreach($data as $row){ echo $row['fullname']; echo "<BR>"; } can anybody help me with that? hi guys i am including a function in my main script, and i'm calling it aftwerwards. except i cannot echo successfully the data in the $result variable, why? function echoResult(){ $result = 'dan'; return $result; } // 1 echo echoResult(); // don't work. i get empty data. // 2 $fnResult = echoResult(); echo $fnResult; // don't work. get empty data. i have ran get_included_files and the include is being made successfully. i read on php.net and these are the examples they use (user comments!) how do i get the data out of the function and echo it, using this way? HI guys I have vreated a site and am now trying to validate the ip address i have created a function but am failing to get it to work i need to add the errors to add to the errors array but instead it keeps resetting and leaving me with the last error that is returned any help would be greatly appreciated im a newbie so if i can understand the concept behind whats happening it will be of great benefit Thanks Sean heres the code // Function validateIpaddress($address,$record,$errors) // { // if ($address !=="" or $address !=="ip_address") // { // Print_r($address); // echo "<br><br>"; // $fullstoppos = strpos(($address), "."); // echo "strpos = $fullstoppos"; // $fullstoppos2 = strpos(($address), ".", $fullstoppos+1); // echo "strpos2 = $fullstoppos2"; // $fullstoppos3 = strpos(($address), ".", $fullstoppos2+1); // echo "strpos3 = $fullstoppos3"; // } // if ($fullstoppos !==4 && $fullstoppos2 !==9 && $fullstoppos3 !==14) // { // $errors[] = "<br><font color='red'>Please correct the following.Or contact your client manager for assitance.<br>* $record is a required field.An ip address is a 16 digit numerical value. </font>"; // } // } $errors = validateIpaddres($_POST['destinationPoint'],A/AAAA record, $errors) |