How to put an Array Value to echo individually - php

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

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

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.

how to get only last value in a foreach? php

foreach ($data['data'] as $data) {
echo $data['title'][0];
//echo '<br />';
}
this will print out:
melon
apple
...
banana
pear
Now, how to jump all, only get the last value in a foreach? only need pear. Thanks.
If you only need the last value, then you don't need to loop. You can use end():
$lastItem = end($data['data']);
echo $lastItem['title'][0];
Note that this will set the internal array pointer to the last element. It might be necessary that you call reset($data) afterwards.
End has already been suggested (which I can recommend actually), however if you want to do it with foreach, you could do:
foreach ($data['data'] as $data) {
}
echo $data['title'][0];
//echo '<br />';
but this is really superfluous. You iterate over the array then only to store the last element into $data. So if there are no elements in 'data' at all this will fail (as with end, but end will return a false if the array is empty).
So go for:
$data=end($data['data']);

How to print out the keys of an array like $_POST in PHP?

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

Output (echo/print) everything from a PHP Array

Is it possible to echo or print the entire contents of an array without specifying which part of the array?
The scenario: I am trying to echo everything from:
while($row = mysql_fetch_array($result)){
echo $row['id'];
}
Without specifying "id" and instead outputting the complete contents of the array.
If you want to format the output on your own, simply add another loop (foreach) to iterate through the contents of the current row:
while ($row = mysql_fetch_array($result)) {
foreach ($row as $columnName => $columnData) {
echo 'Column name: ' . $columnName . ' Column data: ' . $columnData . '<br />';
}
}
Or if you don't care about the formatting, use the print_r function recommended in the previous answers.
while ($row = mysql_fetch_array($result)) {
echo '<pre>';
print_r ($row);
echo '</pre>';
}
print_r() prints only the keys and values of the array, opposed to var_dump() whichs also prints the types of the data in the array, i.e. String, int, double, and so on. If you do care about the data types - use var_dump() over print_r().
For nice & readable results, use this:
function printVar($var) {
echo '<pre>';
var_dump($var);
echo '</pre>';
}
The above function will preserve the original formatting, making it (more)readable in a web browser.
var_dump() can do this.
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
http://php.net/manual/en/function.var-dump.php
I think you are looking for print_r which will print out the array as text. You can't control the formatting though, it's more for debugging. If you want cool formatting you'll need to do it manually.
This is a little function I use all the time its handy if you are debugging arrays. Its pretty much the same thing Darryl and Karim posted. I just added a parameter title so you have some debug info as what array you are printing. it also checks if you have supplied it with a valid array and lets you know if you didn't.
function print_array($title,$array){
if(is_array($array)){
echo $title."<br/>".
"||---------------------------------||<br/>".
"<pre>";
print_r($array);
echo "</pre>".
"END ".$title."<br/>".
"||---------------------------------||<br/>";
}else{
echo $title." is not an array.";
}
}
Basic usage:
//your array
$array = array('cat','dog','bird','mouse','fish','gerbil');
//usage
print_array("PETS", $array);
Results:
PETS
||---------------------------------||
Array
(
[0] => cat
[1] => dog
[2] => bird
[3] => mouse
[4] => fish
[5] => gerbil
)
END PETS
||---------------------------------||
You can use print_r to get human-readable output.
See http://www.php.net/print_r
Similar to karim's, but with print_r which has a much small output and I find is usually all you need:
function PrintR($var) {
echo '<pre>';
print_r($var);
echo '</pre>';
}
//#parram $data-array,$d-if true then die by default it is false
//#author Your name
function p($data,$d = false){
echo "<pre>";
print_r($data);
echo "</pre>";
if($d == TRUE){
die();
}
} // END OF FUNCTION
Use this function every time whenver you need to string or array it will wroks just GREAT.
There are 2 Patameters
1.$data - It can be Array or String
2.$d - By Default it is FALSE but if you set to true then it will execute die() function
In your case you can use in this way....
while($row = mysql_fetch_array($result)){
p($row); // Use this function if you use above function in your page.
}
You can use print_r to get human-readable output.
But to display it as text we add echo '<pre>';
echo '<pre>';
print_r($row);

Categories