How to process variable data within PHP foreach loops - php

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++;
}
?>

Related

PHP key() returning the key for the next item in the array, not the current one

The code here is pretty simple, so I'm not sure what could be happening. This site that I made a couple of years ago has been working fine the whole time, and today I randomly checked on it to find it completely borked. I'm not sure if it was a PHP upgrade performed by my webhost or maybe an automatic WordPress update that broke it, but in any case, the code is not behaving as expected.
In the WordPress loop, for each post, this code is running:
$stats = array(
'recon' => 'Recon',
'inf' => 'Infantry',
'fist' => 'Fire Support',
'atgm' => 'ATGM',
'armor' => 'Armor',
'arty' => 'Artillery',
'aa' => 'Anti-Air',
'air' => 'Aircraft',
'heli' => 'Helicopters'
);
foreach( $stats as $stat_name ):
$stat_key = key( $stats );
// DEBUG:
echo '<p>' . $stat_key . ' : ' . $stat_name . '</p>';
...
next( $stats );
endforeach;
As you can see on the live site, key( $stats ) is returning the key for the next item in the array and not the current one, and returning null for the last item in the array. What could possibly be going wrong here?
Simply make use of the key option in the foreach
foreach( $stats as $key => $stat_name ):
// DEBUG:
echo '<p>' . $stat_key . ' : ' . $stat_name . '</p>';
endforeach;
I wouldn't suggest calling, next while in a foreach loop, it will do the iteration for you. Likely it's already done so when you call key, because its moved the pointer on to the next item already.
Foreach can do weird things when you mess with the structure of the array because it creates a shadow copy of the array (I forget the exact way its explained, and they may have changed it somewhat in 7). In any case, I'm not sure what affect calling next will have, maybe none, because of the way that it handles iterating with foreach. I never tried it!
If you want to use next, then use the do or while loop.
The really proper syntax would be
foreach( $stats as $key => $stat_name ){
// DEBUG:
echo '<p>' . $stat_key . ' : ' . $stat_name . '</p>';
}
The Alternative syntax is useful if you have it in html, such as
<?php foreach( $stats as $key => $stat_name ): ?>
<p><?=$stat_key;?> : <?=$stat_name;?></p>
<?php endforeach; ?>
<div> ....
This is because the endforeach; is more descriptive then the } and it can be very easy to lose track of the } when mixed with HTML and other control structures (like if statements). With the alternative statement you wind up with things like endforeach; endif; instead of } } . Hope that makes sense.

PHP echo array?

Im new at this and not sure how to fill an array and echo it. Can someone please help me? :)
First my array, that I hope is retrieving info from my notes.txt-file, if there is any?! Im not sure if i need both declarations?:
$test = array();
$test[] = json_decode(file_get_contents($file), TRUE);
Anyway, this is the code for adding elements to the array, the input from the user:
$name = guestbook_input($_POST['name']);
$comment = guestbook_input($_POST['comment']);
$test[] = [
'name' => $name,
'comment' => $comment,
'ip' => $_SERVER['REMOTE_ADDR'],
'time' => date("y-m-d H:m")
];
// Write input to file
file_put_contents($file, json_encode($test));
This code works fine (I think) and writes to the file.
Finally Im trying to echo the array to a table like this:
<?php
$getfile = json_decode(file_get_contents('./notes.txt'), TRUE);
foreach ($getfile as $value): ?>
<tr>
<?php
echo '<td>';
echo $value['name'];
echo '</td>';
echo '<td>';
echo $value['comment'];
echo '</td>';
echo '<td>IP:';
echo $value['ip'];
echo "<br>Tid:";
echo $value['time'];
echo '</td>'?>
</tr> <?php endforeach; ?>
This code do print elements, but only for the first input in my guestbook. I have no idea if this is the right way to do this or not, but hopefully someone can help me with this, so I can get this right?!
First, your declaration and assignment:
$test = array();
$test[] = json_decode(file_get_contents($file), TRUE);
The function json_decode(), as you're calling it, returns an array, so it is not necessary to declare the variable first, but it is good practice to do so. However, in the function call, you are actually assigning the entire results to $test[0], since $test[] simply creates a new element with the next numeric index. The code where you assign the user input is correct, so it gets output correctly.
You are putting your array that you read from a file into a single element of the array $test.
Then you are adding your new entry as the second element.
You should initialise the array as:
$test = json_decode(file_get_contents($file), TRUE);

Multiple Objects in Foreach Loop

I have the following two foreach loops that are working for me:
foreach ( $pa_speciesreactivityabbrs as $pa_speciesreactivityabbr ) {
echo '<span>' .$pa_speciesreactivityabbr->name. '</span>';
}
foreach ( $pa_speciesreactivitys as $pa_speciesreactivity ) {
echo '<span>' .$pa_speciesreactivity->name. '</span>';
}
However I need to combine the $pa_speciesreactivityabbrs and $pa_speciesreactivitys in the same loop to output $pa_speciesreactivityabbr->name and $pa_speciesreactivity->name together.
I have gone through a number SO answers from other posts, but can't seem to apply them to my situation.
Looks like your objects are in normal arrays. Assuming you don't use associative arrays, you could do this easily by looping through one of them and output data from both at the same time. Like this:
foreach ($array1 as $index => $obj1) {
echo '<span>' . $obj1->name . $array2[$index]->name . '</span>';
}
I shortened the array names to make it more readable, but I'm sure you see how it works.

Multiple Variable Variables in PHP

I am fairly new to PHP and programming in general... I am attempting to use a foreach loop to set some options on a page I have created. It all works except for the last section, where I am attempting to assign variables dynamically, so I can use them outside the loop.
<?PHP
$array=array(foo, bar, baz);
foreach ($array as $option) {
// I have if statements to determine what $option_req
// and $option_status end up being, they work correctly.
$option_req="Hello";
$option_status="World";
$rh='Req_';
$sh='Status_';
$$rh.$$option=$option_req;
$$sh.$$option=$option_status;
}
echo "<br>R_Foo: ".$Req_foo;
echo "<br>S_Foo: ".$Status_foo;
echo "<br>R_Bar: ".$Req_bar;
echo "<br>S_Bar: ".$Status_bar;
echo "<br>R_Baz: ".$Req_baz;
echo "<br>S_Baz: ".$Status_baz;
?>
When the loop is finished, should this now give me six variables?
$Req_foo
$Status_foo
$Req_bar
$Status_bar
$Req_baz
$Status_baz
I have played with this a bit, searches on Google seem fruitless today.
To access some array item, just access some array item.
No loops required.
$req = array("foo" => 1,
"bar" => 2,
"baz" => 3,
);
echo $req['foo'];
plain and simple
Looks like PHP doesn't like the concatenation when you're trying to do an assignment. Try doing so beforehand, like so:
<?php
$array = array('foo', 'bar', 'baz');
foreach ($array as $option)
{
$option_req="Hello";
$option_status="World";
$rh = 'Req_';
$sh = 'Status_';
$r_opt = $rh.$option;
$s_opt = $sh.$option;
$$r_opt = $option_req;
$$s_opt = $option_status;
}
echo "<br>R_Foo: ".$Req_foo;
echo "<br>S_Foo: ".$Status_foo;
echo "<br>R_Bar: ".$Req_bar;
echo "<br>S_Bar: ".$Status_bar;
echo "<br>R_Baz: ".$Req_baz;
echo "<br>S_Baz: ".$Status_baz;
As other commenters suggested, this isn't a great practice. Try storing your data in an array, rather than just cluttering up your namespace with variables.
You could (though you should not!) do:
${$rh.$option} = ...
Variable variables don't work that way. You need to have one variable containing the string.
$opt_r = $rh.$option;
$$opt_r = $option_req;
$opt_s = $sh.$option;
$$opt_s = $option_status;
Also, make sure to quote your strings:
$array=array('foo', 'bar', 'baz');
I don't suggest using variable variables, but if you want to, this is how to do it.

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