Output (echo/print) everything from a PHP Array - php

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

Related

MYSQLI/PHP How do I have to define my query/statement to output every message that was sent in a particular chatroom? [duplicate]

for output array Instead of using json_encode, use of what.(how is output(echo) array without use of json_encode?)
i use of codeigniter.
CI_Controller:
function auto_complete(){
$hotel_search = $this->input->post('search_hotel');
echo json_encode($this->model_tour->auto_complete($hotel_search));
// if use of json_encode output is '[{"name":"salal"},{"name":"salaso"},{"name":"salasi"},{"name":"salsh"}]' if don want use of json_encode output is "Array"
}
CI_model:
function auto_complete($hotel_search)
{
$query_hotel_search = $this->db->order_by("id", "desc")->like('name', $hotel_search)->get('hotel_submits');
if($query_hotel_search->num_rows()==0){
return '0';
}else{
$data = array();
foreach ($query_hotel_search->result() as $row)
{
$data[] = array('name' => $row->name);
}
return $data;
}
}
If you just want to view the array, print_r($array) or var_dump($array) will work
I'm not sure if this is what you are looking for, but it really helps show the structure of the array/JSON:
echo "<pre>";
print_r($array);
echo "</pre>";
It will show the $array broken out and will keep the tabbing so you can see how it's nested.
If you want to view the contents of the array, use print_r or vardump
If you want to do something useful with the information, you're going to have to loop through the array
foreach($this->model_tour->auto_complete($hotel_search) as $key => $value){
//do something
}
foreach($array as $key => $value)
{
echo $key . ' = ' . $value . "\n";
}
That will give you the array as string.
You can also use print_r()
print_r($array);
or var_dump()
var_dump($array);
You have a few options at your disposal:
json_encode (which you mention yourself)
print_r or var_dump (timw4mail mentions this)
implode (however, this won't work for nested arrays, and it will only display the keys)
a combination of array_map (to format individual array elements using your own function) and implode (to combine the results)
write your own recursive function that flattens an array into a string
If you're using jQuery, any .ajax(), .get(), or .post() function will try to guess the data type being returned from the HTTP request. Set the content type of your controller to JSON:
$hotel_search = $this->input->post('search_hotel');
$this->output
->set_content_type('application/json')
->set_output( json_encode($this->model_tour->auto_complete($hotel_search)) );

Extracting JSON response from JSON Object in PHP [duplicate]

for output array Instead of using json_encode, use of what.(how is output(echo) array without use of json_encode?)
i use of codeigniter.
CI_Controller:
function auto_complete(){
$hotel_search = $this->input->post('search_hotel');
echo json_encode($this->model_tour->auto_complete($hotel_search));
// if use of json_encode output is '[{"name":"salal"},{"name":"salaso"},{"name":"salasi"},{"name":"salsh"}]' if don want use of json_encode output is "Array"
}
CI_model:
function auto_complete($hotel_search)
{
$query_hotel_search = $this->db->order_by("id", "desc")->like('name', $hotel_search)->get('hotel_submits');
if($query_hotel_search->num_rows()==0){
return '0';
}else{
$data = array();
foreach ($query_hotel_search->result() as $row)
{
$data[] = array('name' => $row->name);
}
return $data;
}
}
If you just want to view the array, print_r($array) or var_dump($array) will work
I'm not sure if this is what you are looking for, but it really helps show the structure of the array/JSON:
echo "<pre>";
print_r($array);
echo "</pre>";
It will show the $array broken out and will keep the tabbing so you can see how it's nested.
If you want to view the contents of the array, use print_r or vardump
If you want to do something useful with the information, you're going to have to loop through the array
foreach($this->model_tour->auto_complete($hotel_search) as $key => $value){
//do something
}
foreach($array as $key => $value)
{
echo $key . ' = ' . $value . "\n";
}
That will give you the array as string.
You can also use print_r()
print_r($array);
or var_dump()
var_dump($array);
You have a few options at your disposal:
json_encode (which you mention yourself)
print_r or var_dump (timw4mail mentions this)
implode (however, this won't work for nested arrays, and it will only display the keys)
a combination of array_map (to format individual array elements using your own function) and implode (to combine the results)
write your own recursive function that flattens an array into a string
If you're using jQuery, any .ajax(), .get(), or .post() function will try to guess the data type being returned from the HTTP request. Set the content type of your controller to JSON:
$hotel_search = $this->input->post('search_hotel');
$this->output
->set_content_type('application/json')
->set_output( json_encode($this->model_tour->auto_complete($hotel_search)) );

I have a problems. I need to split string variable in php

I have code which extracting keywords, this keywords with td/idf rating and other options are in $tags. Variable k-keyword consisting of this word. but if i want to print all of these keywords, this keywords look like: one long string, I need to have this keywords separated with " ", or ","...
I have something like that in php
foreach($tags->keywords as $k) {
//$metTag = parseTags($k->keyword);
print_r ($k->keyword);
}
and output is
userarmethodrecommenddelivthidecisconsidactionruleadaptinformmodelcontentsituatbasiengagon-demandproactivmood
but I need output like that:
Array (
[user]
[ar]
[method]
[recommend]
...
)
You can just do
print_r($tags->keywords);
Or this way :
$array = array();
foreach($tags->keywords as $k) {
$array[] = $k->keyword;
}
print_r($array);
Try this:
echo '<pre>';
foreach($tags->keywords as $k) {
print_r ($k->keyword);
}
echo '</pre>';
From the code that you've provided, it looks like $k is an object with the field keyword. Since $tags->keywords is an array you could try to just use print_r($tags->keywords); instead of the loop but this will display all of the fields in the array $tags->keywords as well as dump all of the fields in the $keywords objects within the array. You might also try print_r($k) but again, this will also print all of the fields in the $k object.
Another option would be to simply do this:
print "Array (\n";
foreach($tags->keywords as $k) {
//$metTag = parseTags($k->keyword);
print $k->keyword . "\n";
}
print ")\n"

returning sql array in php

I am having trouble in returning data in php from an SQL query. here is my code:
public function get_audit_message($productId,$accountId)
{
$sql_list ="SELECT notes
FROM ".$this->tables_audit."
WHERE productId = '".mysql_real_escape_string($productId)."'
AND accountId = '".mysql_real_escape_string($accountId)."'
";
$query = $this->db->query($sql_list);
if($query->num_rows() > 0)
{
$return = $query->result_array();
return $return;
}
else return false;
}
the reason I am having trouble is that as it is at return $return; returns the correct number of results but only displays the word "array". then if i change it to return $return[0]; returns the first entry of information correctly.
So what i want to be able to do is select all array numbers e.g return $return[*]; if only was possible.
Any suggestions would be much appreciated.
return $return; is the correct way to return an array from this function, but you can't just echo() the return value, since it's an array. When you try to echo an array, you get just the literal word "Array" (this also raises a notice which you would've seen with error reporting turned on).
You have to iterate over it and print each array element out, or use implode():
$array = $obj->get_audit_message($productId,$accountId); // However you call it
echo implode( "<br />\n", $array) . "<br />\n";
Or:
$array = $obj->get_audit_message($productId,$accountId); // However you call it
foreach( $array as $el) {
echo $el . "<br />\n";
}
Both of the above snippets will produce the exact same output.
There is several easy ways to display content of PHP Array in HTML.
The most simple is to view it via print_r command like this:
print_r ($my_array);
If you need to be "nice" formatted, add PRE tag like this:
echo "<pre>";
print_r($my_array);
echo "</pre>";
or like this:
echo "<pre>".print_r($my_array, 1)."</pre>";
Also, there is similar var_dump and var_export PHP function:
echo "<pre>";
var_dump($my_array);
echo "</pre>";
or
echo "<pre>";
var_export($my_array);
echo "</pre>";
Just choose your preferred stile.

How to parse a web service returned response into an array in PHP

I am updating my question with a few breakthroughs i was able to achieve today. I used get_object_vars.
This code was able to print out the value i am trying to iterate over.
$fileStatus = $ServicesLink->GetFileStatus(array('Ticket'=>$ticket,'ProjectID'=>$pidobtained,'SourceLanguageID'=> "", 'TargetLanguageID'=> "",'FileID'=> "",'Filename'=>""));
$arrayPid = array();
foreach($fileStatus->GetFileStatusResult->FileStatuses->FileStatus as $fileStatusObtained)
{
$arrayPid = get_object_vars($fileStatusObtained);
//$arrayPid =$fileStatusObtained ;
}
echo is_array($arrayPid) ? 'Array' : 'not an Array';
echo "<br>";
echo("Count of array ".count($arrayPid));
echo "<br>";
print_r('<pre>'. print_r($arrayPid) .'</pre>');
This http://www.image-share.com/ijpg-1163-165.html is what i saw as a result.
Now since this Object has objects inside it along with the values i need i.e. FileID,FileName etc. I am seeing the error message but a glimpse of the output. The code i used was this (just a very minor change from the above. I used a foreach)
$fileStatus = $ServicesLink->GetFileStatus(array('Ticket'=>$ticket,'ProjectID'=>$pidobtained,'SourceLanguageID'=> "", 'TargetLanguageID'=> "",'FileID'=> "",'Filename'=>""));
$arrayPid = array();
foreach($fileStatus->GetFileStatusResult->FileStatuses->FileStatus as $fileStatusObtained)
{
$arrayPid = get_object_vars($fileStatusObtained);
//$arrayPid =$fileStatusObtained ;
}
echo is_array($arrayPid) ? 'Array' : 'not an Array';
echo "<br>";
echo("Count of array ".count($arrayPid));
echo "<br>";
//print_r('<pre>'. print_r($arrayPid) .'</pre>');
foreach($arrayPid as $val) {
echo ($val);
echo "<br>";
}
}
As a result of this i saw the following output http://www.image-share.com/ijpg-1163-166.html .
The index number 1 occupies the object and hence the error for string conversion.
If i use a For loop instead of the foreach in the code just above,i am unable to print the values.
I tried:
for($i=0;$i<(count($arrayPid));$i+=1)
{
echo($arrayPid[$i]);
}
But this would print nothing.
Could any one help me with a way so that i can iterate and have the values inside that array $arrayPid.
Would like to have your suggestions, views, doubts on the same.
I am sorry that i am using imageshare but that is the only way i can share my screens.
Thanks
Angie
The correct way to use it is:
foreach($fileStatus->GetFileStatusResult->FileStatuses->FileStatus as $fileStatusObtained)
{
$arrayPid = get_object_vars($fileStatusObtained);
//print_r($fileStatusObtained->FileID);
$fileId [] = $fileStatusObtained->FileID;
...
}

Categories