I'm attempting to print an array of php elements embedded in html
If I input
echo '<strong>'.$s[firstname].' '.$s[lastname].'</strong><div class="moreinfo"><p><small>'.$s[role].' of '.$parent'.</small></p></div></li>';
I get a result that says something like "Chris James Parent of Array
but if I attempt to print the array with a foreach as so
echo '<strong>'.$s[firstname].' '.$s[lastname].'</strong><div class="moreinfo"><p><small>'.$s[role].' of '.
foreach($parent as $p){
echo $p.' ';
}
.'</small></p></div></li>';
The program crashes completely. I would assume that I'm doing something syntactically incorrect, but I can't spot the issue. Is there a simply way to print the elements in thearray that would avoid the crash?
Thanks in advance!
You concatenate output with . not additional PHP statements:
echo '<strong>'.$s[firstname].' '.$s[lastname].'</strong><div class="moreinfo"><p><small>'.$s[role].' of ';
foreach($parent as $p){
echo $p.' ';
}
echo '</small></p></div></li>';
However you can just implode $parent:
echo '<strong>'.$s[firstname].' '.$s[lastname].'</strong><div class="moreinfo"><p><small>'.$s[role].' of '.implode(' ', $parent).'.</small></p></div></li>';
Related
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>;
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];
I have a PHP session array where it can be counted as multidimensional array, basically I am trying to store data inside my session array and i am successfully obtaining that part of the task. The main issue is, I am not able to echo them specifically and I have to use var_dump. When I try to print them with echo i got an notice which says array to string conversion. Please any help I would be appreciated how to print them with their own specific keys or values. The code as follows:
if (!is_array($_SESSION['products']['names'])){
$_SESSION['products']['names'] = array();
$_SESSION['products']['names']['prices']= array();
}else {
$pros = $_SESSION['products']['names'];
if (in_array($product->getName(), $pros, true)){
echo 'The product is available in your basket';
} else {
array_push($_SESSION['products']['names'],$product->getName());
array_push($_SESSION['products']['names']['prices'], $product->getPrice(Currency::getCurrentCurrency()));
foreach ($_SESSION['products'] as $val){
echo $val['names'];
echo $val['prices'];
}
}
}
The output that I receive as follows:
Notice: Undefined index: names in
Array to string conversion in
Use join() function in your foreach, like this:
echo join('<br>', $val);
Or instead of
echo $val['prices'];
write
echo $val['names']['prices'];
This is your problem...
// Here your assigning `['names']` as a string..
array_push($_SESSION['products']['names'],$product->getName());
// Then here you're overwriting the string with an array...
array_push($_SESSION['products']['names']['prices'], $product->getPrice(Currency::getCurrentCurrency()));
Change the first one to this..
array_push($_SESSION['products']['names']['name'],$product->getName());
Assuming $product->getPrice() returns a string or a number...
foreach ($_SESSION['products'] as $val){
foreach($val['names'] as $name){
echo $name['name'];
echo $name['prices'];
}
}
There is no issue with the code you have here. I don't see you trying to echo or vardump them directly so please show the code you are echoing them out specifically or the output from above and which line is giving you an issue.
If you want to echo each one out with it's price.
for($i=0;$i<count($_SESSION['products']['names']);$i++) {
echo $_SESSION['products']['names'][$i] . " " . $_SESSION['products']['names']['price'][$i];
}
I've been using explode in a separate foreach, but now I want to use it in existing foreach, which I find hard. Instead of the name of the screenshot it echos "Array". What am I doing wrong and how can I limit it to just one of the screenshots, not up to four?
<?php $game = Yii::app()->db->createCommand();
$game->select = 'idProgramGame, dk_name, dk_text, picture, recordType, screenshot';
$game->from = 'programsgames';
$game->where = 'dk_name IS NOT NULL';
$game->where = 'featured = 2';
$game->where = 'points = 100';
$game->where = 'recordType = "g"';
$game->order = 'date DESC';
$game->limit = '1';
$gameresult = $game->query();
foreach($gameresult as $gamerow) {
echo '<a href="http://www.domain.com/Yii/index.php/programsgames/';
echo $gamerow['idProgramGame'];
echo '">';
echo '<br><div class="image"><h2><span><b>';
echo $gamerow['dk_name'];
echo '</b></span></h2>';
echo '<center><img src="http://www.domain.com/upload/';
echo explode(';',$gamerow['screenshot']);
echo '" height="250" align="center" alt="';
echo $gamerow['dk_name'];
echo '"></center>';
echo '</a></div><br><br><br>';
}
?>
When trying to debug, you should always simplify your code as much as possible, while still getting the error.
In this case, you've already established that your echo explode(";",$gamerow['screenshot']); line is at fault here, so you should investigate explode and how it works.
In particular, you'll notice that it returns an array. Reading up on arrays will tell you that if you try to just echo it, it outputs Array, literally.
Now, I don't know what's in $gamerow['screenshot'], but I'm going to guess that it's something like this:
something.png;otherstuffhere
If that's the case, then your solution depends on if your PHP is up-to-date.
If it is, just do this:
echo explode(";",$gamerow['screenshot'])[0];
If not, you have to use a temporary variable:
$parts = explode(";",$gamerow['screenshot']);
echo $parts[0];
For future reference, to output the contents of an array for debugging purposes, use var_dump or a related function.
echo explode(';',$gamerow['screenshot']);
explode() will return an array of all values seperated by ';', but echo() can't display arrays. You could just loop through that array from explode() using foreach:
foreach(explode(';',$gamerow['screenshot']) as $screenshot){
echo($screenshot);
}
Maybe the code looks like something like this:
foreach(...$POST){
echo $key."<br/>;
}
var_dump($_POST);
or
print_r($_POST);
You might insert a pre tag before and after for the clearer output in your browser:
echo '<pre>';
var_dump($_POST);
echo '</pre>';
And I suggest to use Xdebug. It provides an enchanted var_dump that works without pre's as well.
See the PHP documentation on foreach:
http://php.net/manual/en/control-structures.foreach.php
Your code would look something like this:
foreach ($_POST as $key=>$element) {
echo $key."<br/>";
}
Tested one liner:
echo join('<br />',array_keys($_POST));
If you want to do something with them programmatically (eg turn them into a list or table), just loop:
foreach ($_POST as $k => $v) {
echo $k . "<br>";
}
For debugging purposes:
print_r($_POST);
or
var_dump($_POST);
And if you want full coverage of the whole array, print_r or even more detailed var_dump
$array = array_flip($array);
echo implode('any glue between array keys',$array);
Or you could just print out the array keys:
foreach (array_keys($_POST) as $key) {
echo "$key<br/>\n";
}
Normally I would use print_r($_POST).
If using within an HTML page, it's probably worth wrapping in a <pre> tag to get a better looking output, otherwise the useful tabs and line breaks only appear in source view.
print_r() on PHP.net