I am having trouble in returning all rows from while loop. When checking with print_r($item) it's returning all rows but when I user return in while loop it is only returning first row. I think that is because it is return the loop at the first time.
So how can I return all rows.. here is what I am trying
while($item = db_assoc($query)){
return '<p>'.$item['title'].'</p>';
}
The while loop is within the class method and I have to return the value so can't use echo
Thanks a lot....
Like you say, you're returning after the first row. Try the following:
$output = '';
while ($item = db_assoc($query)) {
$output .= "<p>{$item['title']}</p>";
}
return $output;
try to Create New Array Or Create format for you want inside the While-loop
And Return it..
"return" it stops execution loop.
while ($item = db_assoc($query)) {
$output .= "<p>{$item['title']}</p>";
}
return $output;
You should use
while($item = mysql_fetch_array($runsql)){
$data[]=$item['first_name'];
}
return $data;
it is because when you write return in loop it return with first value,
but in print_r it shows all record . so we have to create an array of required field and then return it
Hope it will help you.
Try this.
while($item = mysql_fetch_array($runsql)){
$data.=$item['first_name']."<br/>";
}
return $data;
Return will simply get out of the loop that's why it prints only the first row. If you want to return it all, save them in a string and after the while loop just return that string.
The return statement is causing it to break the execution of the loop.
Try this instead:
while($item = db_assoc($query)){
$titles[] = '<p>'.$item['title'].'</p>';
}
And to access the titles, you can simply use a foreach loop:
foreach($titles as $title){
echo "<p> $title </p";
}
Related
I have an small piece of PHP code that needs to put every file in the current directory into an array.
I have done this by making reading the dir with glob() and when it meets another dir it will loop.
My code I have as of now:
<?php
$find = '*';
$result = array();
function find($find)
{
foreach (glob($find) as $entry)
{
$result[] = $entry;
echo $entry.'<br>';
if (is_dir($entry)){
$zoek = ''.$entry.'/*';
find($zoek);
}
}
return $result;
}
print_r(find($find));
?>
When I execute the code the echo print exactly what I want. But the printed array doesn't give me the values I want, it only gives the values in the first dir it will come by then it seems to stop adding the value in the array.
What am I doing wrong?
You need to actually preserve the results you produce in the recursive callings to your function:
<?php
function listNodesInFolder($find) {
$result = [];
foreach (glob($find) as $entry) {
$result[] = $entry;
if (is_dir($entry)) {
$result = array_merge($result, find($entry.'/*'));
}
}
return $result;
}
print_r(find('*'));
Once on it I also fixes a few other issues with your code:
$result should be declared as an array inside your function, that that even if it does not loop you still return an array and not something undefined.
indentation and location of brackets got adjusted to general coding standards, that makes reading your code much easier for others. Get used to those standards, it pays out, you will see.
no need for an extra variable for the search pattern inside the conditional.
a speaking name for the function that tells what it actually does.
you should not name variables and functions alike ("find").
You need to add the result of find() to the array
Edit added array_merge - Cid's idea
<?php
$find = '*';
function find($find)
{
$result = array();
foreach (glob($find) as $entry)
{
$result[] = $entry;
echo $entry.'<br>';
if (is_dir($entry)){
$zoek = ''.$entry.'/*';
$result = array_merge($result, find($zoek));
}
}
return $result;
}
print_r(find($find));
?>
can somone explain me how this code works
<?php
function append($initial)
{
$result=func_get_arg(0);
foreach(func_get_arg()as $key=>value){
if($key>=1)
{
$result .=' '.$value;
}
}
return $result;
echo append('Alex,'James','Garrett');
?>
why do we have a 0 at the func_get_arg(0), and this is a loop there are 0,1,2 shouldn't it only post Alex, James?
and what is the (as) does the func_get_arg() as $key => value. give the array the names to the value ?
this is basic but a bit messy!
That's how it works:
<?php
function append($initial)
{
// Get the first argument - func_get_arg gets any argument of the function
$result=func_get_arg(0);
// Get the remaining arguments and concat them in a string
foreach(func_get_args() as $key=>value) {
// Ignore the first (0) argument, that is already in the string
if($key>=1)
{
$result .=' '.$value;
}
}
// Return it
return $result;
}
// Call the function
echo append('Alex,'James','Garrett');
?>
This function will do the same that:
echo implode(' ', array('Alex', 'James', 'Garrett'));
before you used the foreach{} loop. You have returned 'Alex' which is at position 0.
$result=func_get_arg(0);
foreach(){
}
return $result; //It returns Alex
//foreach() loop
foreach(func_get_arg()as $key=>value){
/*Its looping and only printing after
the key gets to 1 and then the loop goes to 2.Eg: $result[$key]=> $value; */
if($key>=1)
{
$result .=' '.$value;
}
}
If I use return in my function, I will get only one value.
If I use echo, I get all the values. I don't get it.
foreach($matches[0] as $matchbun)
{
$var1 = str_split($matchbun, 34);
$replace_line = "-";
$var_final = str_replace($replace_line, " ", $var1[1]);
$replace_url = array('google.com', '/name/');
$replace_url_with = array('yahoo.com', '/url_');
$url_final = str_replace($replace_url, $replace_url_with, $matchbun);
return ''.ucfirst($url_final).'';
}
Seems that I can't insert the echoes into a database, they appear blank if I run the function.
What to do?
When you have a return the code would not execute further. Generate the whole data, then return that data.
You can either built an array. Like -
$urls= array();
foreach($matches[0] as $matchbun)
{
.....
$urls[]= ucfirst($url_final);
}
return $urls;
Or You can generate a string. Like -
$urls= '';
foreach($matches[0] as $matchbun)
{
.....
$urls.= ucfirst($url_final);
}
return $urls;
Well, if you use return, you'll exit from that function on first iteration.
If you use echo, you are not exiting the function, you are echoing every iteration of the foreach loop.
Take return out of loop. and put data you want to return in a variable. Like this:
foreach($matches[0] as $matchbun)
{
$var1 = str_split($matchbun, 34);
$replace_line = "-";
$var_final = str_replace($replace_line, " ", $var1[1]);
$replace_url = array('google.com', '/name/');
$replace_url_with = array('yahoo.com', '/url_');
$url_final = str_replace($replace_url, $replace_url_with, $matchbun);
$myNewVariable .= $url_final;
}
return $myNewVariable;
I want to use a function to load my news feed on my website dynamically from my database, I have created a function with variables for the type of post, from a specific user etc, and I want to run a while() loop to return each and every post as you would usually, how can this be done within a function though? I tried running the loop and setting the content I want to display in a single variable, which it then returns within that loop, I was hoping it would then run a return each time within the loop and the function would echo each out one by one, when I think about it logically, that obviously wouldn't happen, so could someone explain how this would be achieved?
Example (similar) code:
Accessing the function:
<?php echo getNews(); ?>
The function:
<?php function getNews(){
//query stuff
while($row = mysql_fetch_array($result)){
$return = "Looped data";
return $return;
}
?>
Return stops function executing. You could try something like
function getNews(){
$html = null;
//query stuff
while($row = mysql_fetch_array($result)){
$return = "Looped data";
$html .= $return;
}
return $html;
}
The return should be used out side of the loop
Try this function
<?php function getNews()
{
$return =array()
while($row = mysql_fetch_array($result))
{
$return[] = "Looped data";
}
return $return;
}
?>
With the first return the function breaks and so only the first row is fetched. You can temporarily save the data in an array and return it. When echoing you can then implode() it.
function getNews(){
//query stuff
$result = array();
while($row = mysql_fetch_array($result)){
$result[] = "looped data";
}
return $result;
}
echo implode("<br>\n", getNews());
Getting an array returned can be more useful in the future. Also the function name is more descriptive in my opinion. It doesn't say concat/etc, only get.
You can't use function to return with each loop. Alternatively either you can save the result created in loop to a variable or an array and return the variable/array. Example using variable is:
<?php function getNews() {
//query stuff
$return = "";
while($row = mysql_fetch_array($result)) {
$return .= "Looped data";
}
return $return;
}
?>
If your purpose is just echo the result than do it in function itself without using variable. Array would be better if you want to process something with result.
Hello i am trying to make function with while loop in php but cant getting write here is my code
function mail_detail($mail_detail){
$data= mysql_query("select * from messages where messages.to = '$mail_detail' and to_viewed = 0 ORDER BY messages.id DESC");
while ($result= mysql_fetch_array($data)){
return $result;
}
}
and out put is
$mail_detail= mail_detail($userid)
echo '<li class="read">
<a href="#">
<span class="message">'. $mail_detail['title'].'</span>
<span class="time">
January 21, 2012
</span>
</a>
</li>';
i am not getting all values just getting one value please help
thx
The return statement is terminating your loop and exiting the function.
To get all values, add them to an array in the loop, and then return the array. Like this:
$results = array();
while ($result = mysql_fetch_array($data)) {
$results[] = $result;
}
return $results;
on the side that receives the array
$msgArray = mail_detail($mail_detail);
foreach($msgArray as $msg) {
//use $msg
}
To add on, a function is only able to return once (except for some special circumstances that you should not worry about). Therefore, the first time your function comes across a return statement, it returns the value and exits.
This functionality of return can often be used to your advantage. For example:
function doSomething($code = NULL)
{
if ($code === NULL) {
return false;
}
//any code below this comment will only be reached if $code is not null
// if it is null, the above returns statement will prevent control from reaching
// this point
writeToDb($code);
}
function mail_detail($mail_detail){
$returnArr = array();
$data= mysql_query("select * from messages where messages.to = '$mail_detail' and to_viewed = 0 ORDER BY messages.id DESC");
while ($result= mysql_fetch_array($data)){
$returnArr[] = $result;
}
return $returnArr;
}
This way you return everything returned because you push it in one array and as your loop finishes, the whole array wil be returned. Because just like xbones said, a return breaks your loop!
harinder,Function(mysql_fetch_array($data)) return an array. That means your $result is an array, so when you recevie the $result at view page you have to extract it using foreach look
like this:
foreach($result as $item)
{
echo $item->user(<-here you have to write the column name ,that you want to retrieve)
}
Hence you can get your all results in array.