it there a better way to write the line in php? - 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.

Related

How to process variable data within PHP foreach loops

I am working with PHP 5.6.30 within a WordPress theme. I'm in progress in learning more about foreach loops.
The following is my original code example...
$acf_opt01 = "it_development_projects";
$acf_opt01_field = get_field_object($acf_opt01);
echo '<h4>' . $acf_opt01_field['label'] . '</h4>';
echo $acf_opt01_field['value'];
$acf_opt02 = "it_enhancements";
$acf_opt02_field = get_field_object($acf_opt02);
echo '<h4>' . $acf_opt02_field['label'] . '</h4>';
echo $acf_opt02_field['value'];
..and this is my optimized version so far...
$array_acf_names = array(
'it_development_projects',
'it_enhancements'
);
foreach($array_acf_names as $key=>$acfname) {
//What more should I do here to finish the logic...I'm not sure what to do about $acf_opt01_field, or if its needed.
//get_field_object($acfname);
}
I'm not sure how variables are handled within foreach loops when concatenated with a $key or if there is a better way then that to go about finishing this process. What's a recommendation in finishing this small exercise within the foreach loop so that it produces the same results as my original statements.
Many Thanks!
Like this,
$array_acf_names = array(
'it_development_projects',
'it_enhancements'
);
foreach($array_acf_names as $key=>$acfname) {
$acf_field = get_field_object(acfname);
echo '<h4>' . $acf_field['label'] . '</h4>';
echo $acf_field['value'];
}
I am not sure what you mean by this I'm not sure how variables are handled within foreach loops when concatenated with a $key as you really don't need the key.
Let's compare your original to the loop above
$acf_opt01 = "it_development_projects";
$acf_opt01_field = get_field_object($acf_opt01);
echo '<h4>' . $acf_opt01_field['label'] . '</h4>';
echo $acf_opt01_field['value'];
$acf_opt02 = "it_enhancements";
$acf_opt02_field = get_field_object($acf_opt02);
echo '<h4>' . $acf_opt02_field['label'] . '</h4>';
echo $acf_opt02_field['value'];
In your original $acf_opt01 = "it_development_projects" this string is now in the array you loop over, so the way you have it, it is the $acfname variable now.
On the first iteration
$acfname = $acf_opt01 = "it_development_projects".
Then there is no need to create an extra variable for it, so we can just put it right in get_field_object() function. Then we just make the other variables we need to create a bit more generic. $acf_field instead of $acf_opt01_field or $acf_opt02_field, and then just output the HTML stuff.
Then on the second iteration
$acfname = $acf_opt02 = "it_enhancements", and then the rest is pretty much the same.
As you can see you can do the loop without the $key=> part. However it doesn't really hurt anything to have it in there either.
The main difference with my answer is that it sets up an array ($fieldObjs) that can be accessed partially or fully after it is initially loaded. This lets you prepare it initially, and use it down the page - or you could even json_encode() the field objects array, and use it with Javascript to create the field objects on the page when needed, instead of with PHP all at once in beginning :)
Either way, this should solve your issue. The first version is the bare minimum echos that you have, and the second parts show you the array storage of field objects :)
<?php
$array_acf_names = array(
'it_development_projects',
'it_enhancements'
);
foreach($array_acf_names as $acfName) {
$fieldObj = get_field_object($acfName);
echo "<h4>{$fieldObj['label']}</h4>
{$fieldObj['value']}";
}
?>
It should also be noted that for() loops are faster...
<?php
$array_acf_names = array(
'it_development_projects',
'it_enhancements'
);
$numAcf = count($array_acf_names);
for($acfLoop = 0; $acfLoop < $numAcf; $acfLoop++){
$fieldObj = get_field_object($acfName);
echo "<h4>{$fieldObj['label']}</h4>
{$fieldObj['value']}";
}
?>
Here is the code that stores this data in case you need it later :)
<?php
$array_acf_names = array(
'it_development_projects',
'it_enhancements'
);
$fieldObjs = array();
foreach($array_acf_names as $acfName) {
$fieldObjs[$acfName] = get_field_object($acfName);
}
print_r($fieldObjs); // look at this and then you can look at how to declare vars
// example...
// echo $fieldObjs["it_enhancements"]["label"];
?>
I believe this should work for you. It creates an array of all the field objects once you loop through them so you can access parts of each, or all of them :)
So there is no real point in having key in your foreach loop as your wont use it and no real point to having the var assigning if you aren't using it outside of the loop
$array_acf_names = array(
'it_development_projects',
'it_enhancements'
);
foreach($array_acf_names as $acfname) {
$acf_field = get_field_object($acfname);
echo '<h4>' . $acf_field['label'] . '</h4>';
echo $acf_field['value'];
}
When you use a foreach in a bidimensional array, the value before 'as' going to get the value from each position of the array, maybe this code is helpfully
<?php
$array_acf_names = array(
'it_development_projects',
'it_enhancements'
);
$cont=0;
foreach($array_acf_names as $key) { //$key get the value from each value of the array (if the array is bidimensional)
echo '<h4>'.$key.'</h4>';
echo $cont; //print the 'position' of the array
$cont++;
}
?>

Warning: Invalid argument supplied for foreach()

In the following php code, I am getting the above error. $strings stores the fields coming from database as an array. So why is this error coming? Can someone tells me the solution for this problem, please.
$db_selected = mysql_select_db("chatter",$con);
$mvsql="Select body from feed";
$str=mysql_query($mvsql,$con);$i=0;
while($strings=mysql_fetch_array($str)){
echo $strings["body"] . "<br>";
}
require_once __DIR__ . '/../autoload.php';
$sentiment = new \PHPInsight\Sentiment();
foreach ($strings as $string) {
// calculations:
$scores = $sentiment->score($string);
$class = $sentiment->categorise($string);
// output:
echo "String: $string\n";
echo "Dominant: $class, scores: ";
print_r($scores);
echo "\n";
}
Add this row in your while loop, and use the foreacn on this:
$stringsArr[] = $strings["body"];
Do not use mysql_ functions, because they are deprecated. Use mysqli_ or PDO instead.
while($strings=mysql_fetch_array($str)): the last iteration of the loop, mysql_fetch_array returns false (no more rows). So after this loop, when you go in your foreach loop, $string is false. Just execute your instructions inside the while loop, for each row.
$db_selected = mysql_select_db("chatter",$con);
$mvsql="Select body from feed";
$str=mysql_query($mvsql,$con);$i=0;
require_once __DIR__ . '/../autoload.php';
$sentiment = new \PHPInsight\Sentiment();
while($strings=mysql_fetch_array($str)){
$body = $strings['body'];
// calculations:
$scores = $sentiment->score($body);
$class = $sentiment->categorise($body);
// output:
echo "String: $body\n";
echo "Dominant: $class, scores: ";
print_r($scores);
echo "\n";
}
Please also read this post: Why shouldn't I use mysql_* functions in PHP? , very useful.
You iterate until mysql_fetch_array($str) returns false. I.e. until $strings is no longer an array. foreach expects $strings to be an array.
$strings will be FALSE when the foreach starts.
This is because of the while above it. This loop will loop through all records, till mysql_fetch_array($str) returns FALSE and thus terminates the loop.
You should probably put the foreach code inside the while loop or use the while loop to collect the items you need and loop through those in the foreach loop.

Echoing PHP Array Returns no Result

So, guys, my problem is that i'm creating an array from a mysql column, but, when i echo the array items, it returns me nothing, i'm about this for a while and i'm not seeing a possible error, hope can get some help. Here' s my code: (I know about the mysql to mysqli, but i'm just beginning and trying the logical stuff. :))
$duracao = mysql_query(
"SELECT SUM(fim_periodo-inicio_periodo)/0.01666667 AS mysum
FROM afunda_eleva_$a"
); //THIS $duracao IS INSIDE A FOR LOOP THAT EXECUTES THE QUERY IF A CONDITION IS SATISFIED (DEPENDING ON $a and $prevNum), it is working fine!
while ($row2 = mysql_fetch_assoc($duracao))
{
$duracao_afunda_eleva[] = $row2['mysum'];
}
so, to test some possible problems, i've put:
$i2 = sizeof($duracao_afunda_eleva);
echo $i2;
echo <br>;
which returns me the right size of the array, the problem comes here, i think:
for($i1 = 0 ; $i1 < sizeof($duracao_afunda_eleva); $i1++)
{
echo $duracao_afunda_eleva[$i1] or die("couldn't echo"
. mysql_error());
echo "<br>";
}
and this returns me no value. I really would appreciate any suggestion. Thanks in advance!
Try print_r instead of echo - echo outputs (string)$variable, which in case of an array is just "array". Also, echo is a language construct and not a function, so your or die(...) is problematic, as language constructs don't have return values.
Generally it's better to not use or die(...) constructs, and handle problems correctly (using a defined return value, so cleanup code can run, for example). Also, not being able to output anything with echo would mean that your php/whatever installation is seriously gone bad, at which point you probably won't even reach that line in your code, and even then it won't have anything to do with mysql.
Since the problem is not in the variable, try to use an alias in your MySQL select:
SELECT SUM(fim_periodo-inicio_periodo)/0.01666667 as mysum
Then in your PHP, you can get $row2['mysum'];
It may not solve the problem, but it is a good start.
Personally I use:
$arr = array ( /* ... */ );
echo "<pre>";
var_dump($arr);
echo "</pre>";
In your last for-loop, you use $i++, it should be $i1++
A quick tip is not to use the sizeof function in your for loop. This gets run with each iteration of your loop and you will notice an improvement in performance if you move it outside the loop (or use a foreach loop instead). e.g.
$count = sizeof($duracao_afunda_eleva);
for($i = 0 ; $i < $count; $i++) {
echo $duracao_afunda_eleva[$i] . '<br />';
}
or
// Foreach loop example
foreach ($duracao_afunda_eleva as $key => $value) {
echo $value . '<br />';
}
or what you could also do is this one line
echo implode('<br />', $duracao_afunda_eleva);
Use this code:
for($i1 = 0 ; $i1 < sizeof($duracao_afunda_eleva); $i1++)
{
echo $duracao_afunda_eleva[$i1] or die("couldn't echo". mysql_error());
echo "<br>";
}
You increased $i instead of $i1.
Although, with arrays, it's usually easier to use a foreach loop.
This runs from the first to the last element in the array.
Like so:
foreach ($duracao_afunda_eleva as $value) {
echo $value;
}
I would also suggest removing the space in $row2 ['mysum']:
$duracao_afunda_eleva[] = $row2['mysum'];
Edit
Just noticed it now, but your fetch-statement is wrong... It has a typo in it:
while ($row2 = mysql_fetch_assoc($duracao))
Make sure it reads mysql instead of myqsl.

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.

PHP nested loop behaving unexpectedly

I have an array which contains the categories for a particular article ($link_cat). I'm then using mysql_fetch_array to print out all of the categories available into a list with checkboxes. While it's doing this I want it to compare the value it's on, to a value from the other array. If there is a match, then it means that one of the categories applies to this article, and it should print out a line of code to apply the checked attribute. great! except it's not working =[
while ( $row = mysqli_fetch_array($results, MYSQLI_ASSOC) ){
$cat[$i] = $row['category'];
$cat_id[$i] = $row['cat_id'];
echo '<li><input type="checkbox" ';
$catCount = count($link_cat);
for ($ct = 0; $ct < $catCount; $ct++){
if ($cat_id[$i] == $link_cat[$ct]){
echo 'checked="checked" ';
}
}
echo 'name="' . $cat_id[$i] . '" />' . $cat[$i] . '</li>';
$i++;
}
I've never really done a nested loop before (I suspect thats the problem).
The problem seems to be that when this runs, $link_cat[0] which will have the first category to check against in it - doesn't register. It comes up blank. Printing out variables inside the for loop confirmed this. Any others [1] [2] etc, are fine. It's just [0]. But why? it doesn't seem to make any sense. I know there is something in there, because I printed the contents of array as I filled it it, just to check. Yet it doesn't just show during the loop. Any ideas?
slight bug fix (and blatant style change): Your version can print out checked="checked" multiple times. Do $cat and $cat_id need to be arrays?
while ( $row = mysqli_fetch_array($results, MYSQLI_ASSOC) ) {
$cat = $row['category'];
$cat_id = $row['cat_id'];
echo '<li><input type="checkbox" ';
if ( in_array($cat_id, $link_cat) ) {
echo 'checked="checked" ';
}
echo "name='$cat_id' />$cat</li>";
}
For situation where one would normally throw a debugger at a problem, I like to throw in a nice print_r in a comment block (view-source for debug output, safer on live-ish sites).
echo '<!-- ' . print_r($link_cat, TRUE) . ' -->';
While I was originally very wrong about the array looping needing a reset, I can't shake the feeling that looping through that array isn't the fastest way to do what you are after.
Perhaps array_search would do, or maybe array_key_exists. in_array look like a winner but I didn't think of it

Categories