PHP foreach statement - php

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.

Related

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>;

How to put an Array Value to echo individually

I want to echo the array on a different location but I cannot make it to work.
i can echo the array if I do these
foreach($domain as $value) {
echo $value;
}
bot cannot echo it individually
foreach($domain as $value) {
$domainame[] = $value;
}
echo '<p> your first domain' .$domainname[0];
echo '<p> your last domain' .$domainname[5];
There are many ways to do this:
var_export($array);
var_dump($array);
print_r($array);
For each of the above it's useful to first ( when outputting to html )
echo "<pre>";
A pre tag to preserve the white space. Each one of these have some uniqueness to them. While I cant cover them all.
var_export - outputs valid PHP comparable text, so you can paste an array right into your code after outputting it with this. It has a second argument $string = var_export($array,true) that will return it as a string
var_dump - tells you the type of variable, such as int, array etc..
print_r - is more "human" readable.
If you want to get really wild you can use, array_map instead of a loop:
array_map(function($item){
echo $item;
}, $array);
At first one would think you could simply do
array_map('echo', $array);
But, alas echo is not a real function, it's a language construct, so you have to wrap it in a closure. Compare this to var_dump
array_map('var_dump', $array )
Works just fine.
And last but not least you could always do
echo json_encode($array);
But that probably won't be to readable.
I am sure there are some I am forgetting.
UPDATE
I thought you just wanted to generally output it. Anyway, you can use array_map
array_map(function($item){
echo "<p> your first domain{$domainame[0]}</p>"; //dont forget the typo
}, $array);
I think #Alive to Die, got it with the typo. But, if you output it using any of the above you would see it was empty.
One thing I should mention, as you should have gotten a warning for this, when developing you should have error reporting turned on ether globally in the php.ini or at least in the file your working on
<?php
error_reporting(-1); //error level E_ALL
ini_set('display_errors', 1); //output errors
you can simply write:
echo '<p> your first domain' .$domain[0];
echo '<p> your last domain' .$domain[5];
no point of looping at all!
you have to do like this
$i = 0;
foreach($domain as $value){
$domainame[$i] = $value;
$i++;
}
and now you can do this
echo '<p> your first domain' .$domainname[0];

PHP display order for iterating through multiple arrays

In essence, I have 3 arrays. These are serialised, stored to the DB, un-serialised and then outputted to a page. myFirstArray, mySecondArray, & myThirdArray.
From what I gather - I need to be using a foreach loop, or a for loop with a counter, as the 3 arrays are all of (the same) unknown length. By that I mean one user may have stored 4 items into each of the 3 arrays, but another user might have stored 8 items into each of the 3 arrays.
I'm trying to get the output to look something like this:
myFirstArray[0], mySecondArray[0], myThirdArray[0]
myFirstArray[1], mySecondArray[1], myThirdArray[1]
myFirstArray[2], mySecondArray[2], myThirdArray[2]
The current code I have is as follows:
foreach ($myFirstArray as $value1){
echo $value1 . " ";
}
foreach ($mySecondArray as $value2){
echo $value2 . " ";
}
foreach ($myThirdArray as $value3){
echo $value3 . "<br>";
}
I am aware that this code is never going to output my arrays as I would like, but I'm having some difficulty with working out the logic behind what I need. I haven't rushed straight to StackOverflow to ask, but nothing else I've seen has been very helpful!
Since both arrays have the same length, I propose
$length = count($myFirstArray);
for($i = 0; $i <$length ; $i++) {
echo $myFirstArray[$i].','.$mySecondArray[$i].','.$myThirdArray[$i].'<br/>';
}
This will loop through all of your arrays at the same time :) .

How Can I Pull An Entire Result From A Foreach Loop

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

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