How Can I Pull An Entire Result From A Foreach Loop - php

I want to get the result from a foreach loop, but use it outside of the foreach brackets. What is the easiest way to do this.
Currently the below is working fine:
foreach($esmc->find('p') as $paragraph){
$showparag = $paragraph->innertext. '<br/>';
echo $showparag;//Will show result of array
}
However, I would like to have this so I can add text to it (echo is outside of foreach brackets):
foreach($esmc->find('p') as $paragraph){
$showparag = $paragraph->innertext. '<br/>';
}
echo "This shows results of array as $showparag";//Contains text + array
Currently if I do the second example, it is only returning the final record in the array.
Any help would be greatly appreciated.

$string = 'This shows results of array as ';
foreach($esmc->find('p') as $paragraph){
$showparag = $paragraph->innertext. '<br/>';
$string .= $showparag;
}
echo $string;
http://php.net/manual/en/language.variables.scope.php
P.S. Despite there is a lot examples of global variables usage in the manual, you actually should not use it as it is considered as a bad practice.

Your questions is rather vague, if this isn't what you want, can you please clarify in the comments.
This, however should generate a string for you to print all of the results as one string, outside of the foreach loop.
$showparag
foreach($esmc->find('p') as $paragraph){
$showparag .= $paragraph->innertext. '<br/>';
}
echo "This shows results of array as $showparag";//Contains text + array

Related

PHP foreach statement

I am a student with PHP and I have a question from this course I am taking which I am able to produce my own solution which works, however the course uses some sort of "fill in the blank" testing method on their web page which means parts of the code cannot be edited.
Basically I have this right now:
<?php
$myArray = array(2,4,6,8);
foreach($myArray as $value)
echo "Points are $value\n";
?>
But it prints "Points are 2 Points are 4 Points are 6 Points are 8"... It needs to print Points are 2 4 6 8 (so print a value with each loop with a space). I know that there is a method that measures the number of arrays against what is being printed before it stops, however I haven't been able to figure it out.
EDIT: Here is the actual question from the webpage of my school's course:
<?php
$numberstring = $_GET['numberstring'];
$numberarray = explode(',',$numberstring);
//your code here
echo "Points are $value\n";
?>
To put them together you can join them.
echo 'Points are ', implode(' ', $myArray), PHP_EOL;
Edit:
After you updated your question, use this as answer to the 2nd part:
$points is empty, so you can directly use implode on $numberrray.
echo 'Points are ', implode(' ', $numberarray), PHP_EOL;
Foreach loops do everything in the loop, every time. Easy mistake, you'll get used to it.
<?php
$myArray = array(2,4,6,8);
echo "Points are ";
foreach($myArray as $value)
echo $value." ";
?>
echo "\n";
See Markus Zeller's answer for a better way to do this, if your predefined code templates allow it.

Echo an Array and make the content look pretty on the page

I am trying to echo out my array on each line, not bunched together.
I have tried <br />, this only show's on the front end, but when you look at HTML code. Its still clumped together.
$arrays = [];
$arrays[] = "Good";
$arrays[] = "Bad";
foreach ($arrays as $array){
echo $array;
}
Result:
GoodBad
Want Result:
Good
Bad
Short of using print_r, to quickly get your desired result, just make this small change:
echo $array."\n";
Make sure it's double-quotes and it will add a new line.
(That would do what "<br />" does on HTML)
Try using print_r($arrays). docs here.
Try echo "<pre>; var_dump($arrays); echo "</pre>;

PHP JSON foreach Array Issue

I'm trying to use PHP to display some JSON data from an API. I need to use foreach to return all my results but nested within them is an array. The array is "highlights" which sometimes has "description" and sometimes "content" and sometimes both. I need to do a foreach within a foreach or something along those lines but everything I try just returns "Array".
Here's the JSON...
https://api.data.gov/gsa/fbopen/v0/opps?q=lte+test+bed+system&data_source=FBO&limit=100&show_closed=true&api_key=CTrs3pcYimTdR4WKn50aI1GcUxyL9M4s1fyBbSer
Here's my PHP...
$json_returned = file_get_contents("JSON_URL");
$decoded_results = json_decode($json_returned, true);
echo "Number Found:".$decoded_results['numFound']."</br> ";
echo "Start:".$decoded_results['start']."</br>";
echo "Max Score:".$decoded_results['maxScore']."</br>";
foreach($decoded_results['docs'] as $results){
echo "Parent Link T:".$results['parent_link_t']."</br>";
echo "Description:".$results['highlights']['description']."</br>";
}
Obviously the working version I'm using has a lot more fields programmed in but I cut them out to keep this code short and simple and show how I have everything else besides the "hightlights" field in one foreach. The JSON returns require that I keep everything in that foreach, so how to I display the array inside of it?
Thanks for any help and thanks for taking the time to read this even if you can contribute.
The 'description' is array with one element so you can use this.
echo 'Description:' . $results['highlights']['description'][0];
If it sometimes has 'description' and sometimes 'content'. Use isset to check which one it is, or even if there are both and print accordingly.
// for description
if(isset($results['highlights']['description'])) {
echo 'Description:' . $results['highlights']['description'][0];
}
// for content
if(isset($results['highlights']['content'])) {
echo 'Content:' . $results['highlights']['content'][0];
}
Hope this helps.
Look into the php array_column() function: http://php.net/manual/de/function.array-column.php

It is not ouputting values in array when echoed

I think there is a problem when I echo $whereArray and orderByArray. If I type in a word such as "Question" and then submit it, I expect it to display in the echos "%".Question."%"; for both arrays. But instead in both echos it just displays "Array" for both echos. Does this mean that both arrays are not working when it comes to storing in the values?
$searchquestion = $_GET['questioncontent'];
$terms = explode(" ", $searchquestion);
$whereArray = array();
$orderByArray = array();
//loop through each term
foreach ($terms as $each) {
$i++;
$whereArray[] = "%".$each."%";
$orderByArray[] = "%".$each."%";
}
echo $whereArray;
echo $orderByArray;
echo() only works for strings. PHP converts your array to "Array" as a fallback.
When you're debugging, you should use var_dump(). It will tell you the type of the object and its content.
Use var_dump or print_r instead of echo (they are functions, not constructs like echo is).
An array needs to be printed out using a special function such as print_r. If you want to print out a value in your array try:
echo $whereArray[0];
To get the first element. Be careful because if the array is empty you will get an error.
you can also loop through them
foreach($arrayname as $value)
echo $value;
or
echo implode("",$arrayname);

a very hard result to foreach in php

$content is an arry. when i print_r($content) the result is too long. now i
echo $fenlei=$content['body']['#object']->field_fenlei['zh-hans'][0]['taxonomy_term']->name;
the result of $fenlei is java. but there maybe many values of $fenlei. eg:
$content['body']['#object']->field_fenlei['zh-hans'][0]['taxonomy_term']->name;
$content['body']['#object']->field_fenlei['zh-hans'][1]['taxonomy_term']->name;
$content['body']['#object']->field_fenlei['zh-hans'][2]['taxonomy_term']->name;
......
how to loop out the
$content['body']['#object']->field_fenlei['zh-hans'][1]['taxonomy_term']->name;
$content['body']['#object']->field_fenlei['zh-hans'][2]['taxonomy_term']->name;
value. it too hard for me. :)
You can store the common code and foreach next:
$common = $content['body']['#object']->field_fenlei['zh-hans'];
foreach($common as $key => $value){
echo "{$key}: " . $value['taxonomy_term']->name;
}
If you want to print out large arrays that are difficult to read you can try:
echo '<pre>'.print_r($array, true).'</pre>';
It makes arrays a little more pretty.

Categories