php My foreach loop dont echo out - php

include 'api/apiBase.php';
$farray[] = GetUserFriends($login->User_id);
foreach ($farray as $FID)
{
echo "$FID \n";
}
My foreach loop won't echo out the array.
the function that i have GetUserFriends Returns 2 variables in a array.

Ok comments dont seem to be working so change your code to this
include 'api/apiBase.php';
// following line changed
$farray = GetUserFriends($login->User_id);
echo $login->User_id . ' has ' . count($farray) . ' friends';
foreach ($farray as $idx => $value)
{
echo "Friend $idx has FriendId $value \n";
}
This line $farray[] = GetUserFriends($login->User_id); with the extra [] in is adding another level to the $farray that you dont need and is confusing you.

That's because you're putting the friends array inside another array, like several comments say. – Barmar
Ohh the error was in my function :) Thanks

Related

How to retrieve array element one by one in PHP?

Hi am trying to read a directory for html files and put them in array and retrieve one by one.
i used following code
$filelist = glob($directory."/*.html");
$val=natsort($filelist); // Sort the array
foreach($filelist as $key => $value)
{
echo " $value , ";
}
$next=0;
$ns=$next+"1";
$filelist1=$filelist[$ns];
echo $filelist1;
am getting html files in a array but not able to retrieve one by one
please suggest
Thanks
That's echoing each item, not returning an array. Maybe it would be more clear if you change
echo " $value , ";
to
echo "ITEM $value ENDITEM , ";
Works for me
$directory = "./dir";
$filelist = glob($directory."/*.html");
sort($filelist);
foreach ($filelist as $filename) {
echo "$filename, ";
}
Also you may use
echo implode(', ', $filelist);
Instead of foreach
Return result like this:
./dir/christmas_en.html, ./dir/christmas_fr.html, ./dir/etpl_winphone.html,

Updating and Sorting a Multidimensional PHP Array

I have a mySQL query that dumps into an array, is sorted and then displayed, and that works perfectly.
My problem is that I want to update these values, re-sort them and display. I've been able to update the values, but it's within the same for loop and so it doesn't re-sort. So then I close the loop and re-sort but it doesn't save the updates I made in the first loop. Help is much appreciated.
foreach ($arr as $mks){
if ($mks['Column1']==$Var) {$mks['Column2'] = $mks['Column2'] + 1;
}
My sorting code
foreach ($arr as $mks){
echo $mks['Column1'] . ", " . $mks['Column2'] . "<br>";
}
How do I get this to re-save into my array properly?! I've tried googling this for most of the morning but has lead to frustration.
I think this is what you need:
foreach ($arr as $key => $mks){
if ($mks[$key] == $Var) {
$arr[$key] = $mks+1;
}
}
Now, $arr will contain the modified array, and you can use / modify it further as you need.
I don't see any "sorting code" but you can try to use references "&" instead of copy vars in your foreach(s) :
foreach($arr as & $mks){
...
}
Instead of copying your cells it will to give you a reference and every modifications done on it will be saved in the array.
Try changing your array like this instead
foreach ($arr as $key => $mks){
if ($mks['Column1']==$Var) {$arr[$key]['Column2'] = $mks['Column2'] + 1;
}

unserialize() value insert with serialize() of database.?

i insert in database values (array) with use function serialize(), how can echo they with unserialize() in tag <ul><li>...?
i have in database this: a:6:{i:0;s:15:"Coffee";i:1;s:14:"Satellite";i:2;s:11:"Game Notes";i:3;s:14:"Internet";i:4;s:10:"Pool";i:5;s:0:"";}
LIKE:
Coffee
Game Notes
Internet
Pool
You need to use unserialize(), as you said, with a foreach() loop, like this:
$arr = unserialize($dbString);
echo "<ul>";
foreach($arr as $key => $val)
{
echo "<li>$val</li>";
}
echo "</ul>";
This will echo a list containing value because foreach() iterates through the unserialize()d array, as you have specified in your question.
The $key => $part is the icing on the cake for foreach(); if you want the get the array key, simply reference $key. If you want the data for that key, use $val.
If you want to echo just one element (your example is Internet), just don't use a loop and reference it by key (integer):
$arr = unserialize($dbString);
echo $arr[2];
This echos the third element in the array on it's own.
Original question
Unserialize the data and loop over it printing it out. Notice that I have also added in checks to see that we are getting back an array and that it contains something before looping over it.
$data = unserialize($row['like']);
if(is_array($data) and count($data)) {
echo '<ul>';
foreach($like as $value) {
echo '<li>' . $value . '</li>';
}
echo '</ul>';
}
Internet
I think this is what you are asking for. To only echo out the value if its Internet.
$data = unserialize($row['like']);
if(is_array($data) and count($data)) {
echo '<ul>';
foreach($like as $value) {
if('Internet' != $value) {
continue;
}
echo '<li>' . $value . '</li>';
}
echo '</ul>';
}
JSON
If you can I would stop using serialize and use json_encode instead. It is easier to encode and decode in more programming languages and it is easier to edit by humans should you need to update the DB directly.

PHP : how to use foreach loop inside an echo statement?

i am tring to put a loop to echo a number inside an echo ;
and i tried as bellow :
$array = array();
$result = mysql_query("SHOW TABLES FROM `st_db_1`");
while($row = mysql_fetch_row($result) ){
$result_tb = mysql_query("SELECT id FROM $row[0] LIMIT 1");
$row_tb=mysql_fetch_array($result_tb);
$array[] = $row[0];
$array2[] = $row_tb[0];
//checking for availbility of result_tb
/* if (!$result_tb) {
echo "DB Error, could not list tablesn";
echo 'MySQL Error: ' . mysql_error();
exit;
} */
}
natsort($array);
natsort($array2);
foreach ($array as $item[0] ) {
echo "<a href=show_cls_db.php?id= foreach ($array2 as $item2[0]){echo \"$item2[0]\"}>{$item[0]}<br/><a/>" ;
}
but php is not considering foreach loop inside that echo ;
please suggest me something
As mentioned by others, you cannot do loops inside a string. What you are trying to do can be achieved like this:
foreach ($array as $element) {
echo "<a href='show_cls_db.php?id=" . implode('', $array2) . "'>{$element}</a><br/>";
}
implode(...) concatenates all values of the array, with a separator, which can be an empty string too.
Notes:
I think you want <br /> outside of <a>...</a>
I don't see why you would want to used $item[0] as a temporary storage for traverser array elements (hence renamed to $element)
Just use implode instead of trying to loop the array,
foreach ($array as $item)
{
echo implode("",$array2);
}
other wise if you need to do other logic for each variable then you can do something like so:
foreach ($array as $item)
{
echo '<a href="show_details.php?';
foreach($something as $something_else)
{
echo $something_else;
}
echo '">Value</a>';
}
we would have to see the contents of the variables to understand what your trying to do.
As a wild guess I would think your array look's like:
array(
id => value
)
And as you was trying to access [0] within the value produced by the initial foreach, you might be trying to get the key and value separate, try something like this:
foreach($array as $id => $value)
{
echo $id; //This should be the index
echo $value; //This should be the value
}
foreach ($array as $item ) {
echo "<a href=\"show_cls_db.php?id=";
foreach ($array2 as $item2) { echo $item2[0]; }
echo "\">{$item[0]}<br/><a/>" ;
}
No offense but this code is... rough. Post it on codereview.stackexchange.com for some help re-factoring it. A quick tip for now would be to use PDO, and at the least, escape your inputs.
Anyway, as the answers have pointed out, you have simply echoed out a string with the "foreach" code inside it. Take it out of the string. I would probably use implode as RobertPitt suggested. Consider sorting and selecting your data from your database more efficiently by having mysql do the sorting. Don't use as $item[0] as that makes absolutely no sense at all. Name your variables clearly. Additionally, your href tag is malformed - you may not see the correct results even when you pull the foreach loop out of the echo, as your browser may render it all away. Make sure to put those quotes where they should be.

it there a better way to write the line in php?

<div class="meta">
<?php echo $submitted."pubblished in".$fenl; ?>
<a href="<?php echo base_path().'comp/'.$node->nid;?>">
<?php echo $comment_count;?>comment</a>
</div>
it there a better way to write the above code.
2,
function blog_gettag(){
$terms = mysql_query('SELECT vid,name FROM term WHERE vid=2');
$items = array();
foreach ($terms as $term){
$items[] = $term->name;
}
return $items;
}
could i delete $items = array(); this line. thank you.
Not really, unless you count the short-tags, but they are frowned on.
Technically, it would be created automatically, but you should pre-declare the empty array, it should generate a warning if you did not.
NB. If you have two separate questions, they should be asked separately in future.
What about one line?
<?php
echo "<div class=\"meta\">\n{$submitted}published in$fenl\n<a href=\"" .
base_path() . "comp/{$node->nid}\">\n$comment_count\ncomment</a>\n</div>";
?>
You could delete $items = array(); as long as $items isn't used before in your script (just don't return $items in case $terms isn't an array and the foreach loop gets called, as the situation seems to be at the moment). I believe you need to check mysql_query() examples at http://php.net/manual/en/function.mysql-query.php.
It's syntactically pretty okay. As far as I know, you could omit $items = array(); but I find it more readable if you just leave it as it is.
Btw.: Don't you need to use mysql_fetch_assoc for your iteration? mysql_query returns a resource.
echo "<div class=\"meta\">" . $submitted . " pubblished in " . $fenl . "" . $comment_count . " comment</div>";
You don't need to define array. But in this case ( foreach issue. Foreach loop requires an array as parameter to left side the "as". If you delete that line $items wouldn't be an array.It will be a null variable.So you will get a warning. ) it should be defined.

Categories