Difference between var_dump,var_export & print_r - php

What is the difference between var_dump, var_export and print_r ?

var_dump is for debugging purposes. var_dump always prints the result.
// var_dump(array('', false, 42, array('42')));
array(4) {
[0]=> string(0) ""
[1]=> bool(false)
[2]=> int(42)
[3]=> array(1) {[0]=>string(2) "42")}
}
print_r is for debugging purposes, too, but does not include the member's type. It's a good idea to use if you know the types of elements in your array, but can be misleading otherwise. print_r by default prints the result, but allows returning as string instead by using the optional $return parameter.
Array (
[0] =>
[1] =>
[2] => 42
[3] => Array ([0] => 42)
)
var_export prints valid php code. Useful if you calculated some values and want the results as a constant in another script. Note that var_export can not handle reference cycles/recursive arrays, whereas var_dump and print_r check for these. var_export by default prints the result, but allows returning as string instead by using the optional $return parameter.
array (
0 => '',
1 => false,
2 => 42,
3 => array (0 => '42',),
)
Personally, I think var_export is the best compromise of concise and precise.

var_dump and var_export relate like this (from the manual)
var_export() gets structured
information about the given variable.
It is similar to var_dump() with one
exception: the returned representation
is valid PHP code.
They differ from print_r that var_dump exports more information, like the datatype and the size of the elements.

Related

How do i output an Array in PHP with JSON data in it? [duplicate]

I have this array
Array
(
[data] => Array
(
[0] => Array
(
[page_id] => 204725966262837
[type] => WEBSITE
)
[1] => Array
(
[page_id] => 163703342377960
[type] => COMMUNITY
)
)
)
How can I just echo the content without this structure?
I tried
foreach ($results as $result) {
echo $result->type;
echo "<br>";
}
To see the contents of array you can use:
print_r($array); or if you want nicely formatted array then:
echo '<pre>'; print_r($array); echo '</pre>';
Use var_dump($array) to get more information of the content in the array like the datatype and length.
You can loop the array using php's foreach(); and get the desired output. More info on foreach is in PHP's documentation website: foreach
This will do
foreach($results['data'] as $result) {
    echo $result['type'], '<br>';
}
If you just want to know the content without a format (e.g., for debugging purposes) I use this:
echo json_encode($anArray);
This will show it as a JSON which is pretty human-readable.
There are multiple functions for printing array content that each has features.
print_r()
Prints human-readable information about a variable.
$arr = ["a", "b", "c"];
echo "<pre>";
print_r($arr);
echo "</pre>";
Array
(
[0] => a
[1] => b
[2] => c
)
var_dump()
Displays structured information about expressions that includes its type and value.
echo "<pre>";
var_dump($arr);
echo "</pre>";
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
var_export()
Displays structured information about the given variable that returned representation is valid PHP code.
echo "<pre>";
var_export($arr);
echo "</pre>";
array (
0 => 'a',
1 => 'b',
2 => 'c',
)
Note that because the browser condenses multiple whitespace characters (including newlines) to a single space (answer), you need to wrap above functions in <pre></pre> to display result in thee correct format.
Also, there is another way to print array content with certain conditions.
echo
Output one or more strings. So if you want to print array content using echo, you need to loop through the array and in the loop use echo to print array items.
foreach ($arr as $key=>$item){
echo "$key => $item <br>";
}
0 => a
1 => b
2 => c
You can use print_r, var_dump and var_export functions of PHP:
print_r: Convert into human-readable form
<?php
echo "<pre>";
print_r($results);
echo "</pre>";
?>
var_dump(): will show you the type of the thing as well as what's in it.
var_dump($results);
foreach loop: using a for each loop, you can iterate each and every value of an array.
foreach($results['data'] as $result) {
echo $result['type'] . '<br>';
}
Try using print_r to print it in human-readable form.
foreach($results['data'] as $result) {
echo $result['type'], '<br />';
}
or echo $results['data'][1]['type'];
You don’t have any need to use a for loop to see the data into the array. You can simply do it in the following manner:
<?php
echo "<pre>";
print_r($results);
echo "</pre>";
?>
Human-readable (for example, can be logged to a text file...):
print_r($arr_name, TRUE);
You can use var_dump() function to display structured information about variables/expressions, including its type and value, or you can use print_r() to display information about a variable in a way that's readable by humans.
Example: Say we have got the following array, and we want to display its contents.
$arr = array ('xyz', false, true, 99, array('50'));
print_r() function - Displays human-readable output
Array
(
[0] => xyz
[1] =>
[2] => 1
[3] => 99
[4] => Array
(
[0] => 50
)
)
var_dump() function - Displays values and types
array(5) {
[0]=>
string(3) "xyz"
[1]=>
bool(false)
[2]=>
bool(true)
[3]=>
int(100)
[4]=>
array(1) {
[0]=>
string(2) "50"
}
}
The functions used in this answer can be found on the PHP documentation website, var_dump() and print_r().
For more details:
How to display PHP variable values with echo, print_r, and var_dump
How can I echo an array in PHP?
If you want a parsable PHP representation, you could use:
$parseablePhpCode = var_export($yourVariable,true);
If you echo the exported code to a file.php (with a return statement) you may require it as
$yourVariable = require('file.php');
I checked the answers, however, (for each) in PHP it is deprecated and no longer works with the latest PHP versions.
Usually, we would convert an array into a string to log it somewhere, perhaps debugging, test, etc.
I would convert the array into a string by doing:
$Output = implode(",", $SourceArray);
Whereas:
$output is the result (where the string would be generated
",": is the separator (between each array field).
$SourceArray: is your source array.
If you only need echo 'type' field, you can use function 'array_column' like:
$arr = $your_array;
echo var_dump(array_column($arr['data'], 'type'));
Loop through and print all the values of an associative array, You could use a foreach loop, like this:
foreach($results as $x => $value) {
echo $value;
}

Creating arrays that aren't indexed properly

I'm trying to figure out someone else's code that doesn't work at my company any more.
I have a variable set $row[9]. The data is from a CSV file that the php parses. The var_dump looks like this
When I try to put $row[9] into an array by doing this $school = explode(",", $row[9])
var_dump($school) outputs this.
print_r($school) outputs this.
print_r
Shouldn't $school look something like this below?
[0] => array(1) {[0] => string(8) "2/3-AM"}
[1] => array(1) {[0] => string(8) "2/3-AM"}
[2] => array(1) {[0] => string(8) "1/2B-AM"}
Let me know if I need to add any other information.
It appears if the first screenshot is all values that $row[9] takes. As if it is iterating over a list, $row[9] has multiple values between the beginning and end of execution. It is not an array of all of those values; it is each of those values individually.
If you were to explode(',', $each_value), then each value will become array( [0] => $each_value ), since each value does not contain a comma.
Given you anticipated output, it seems you expect $row[9] to be an array of those strings, when it is simply a string that changes value over time.

Get array out of a Json?

I am getting a Json respond with :
$response = curl_exec($rest);
$json = json_decode($response, true);
I manage to get its values(strings) with :
$foundUserId=$json['results'][0]['userId'];
$foundName=$json['results'][0]['name'];
$foundPhoneNum=$json['results'][0]['phoneNumber'];
But the last value- phoneNumber, is array of strings .
If i try then to loop over it i get nothing(although the array is there in the Json)
foreach ($foundPhoneNum as &$value)
{
print_r($value);
}
What am i doing wrong ?
EDIT :
The json:
Array ( [results] => Array ( [0] => Array ( [action] => message [createdAt] => 2015-11-21T09:36:33.620Z [deviceId] => E18DDFEC-C3C9 [name] => me [objectId] => klMchCkIDi [phoneNumber] => ["xx665542","xxx9446"] [state] => 1 [updatedAt] => 2015-11-22T08:24:46.948Z [userId] => 433011AC-228A-4931-8700-4D050FA18FC1 ) ) )
You might have json as a string inside json. That's why after json_decode() you still have json inside phoneNumber. You have 2 options:
Decode phoneNumber like
$foundPhoneNum=json_decode($json['results'][0]['phoneNumber']);
Build proper initial json. Instead of
{"phoneNumber": "[\"xx665542\",\"xxx9446\"]"}
should be
{"phoneNumber": ["xx665542","xxx9446"]}
There's a couple of ways to debug situations like this as mentioned in the comments; print_r() and var_dump().
var_dump(), although harder to read the first few times, is my favourite because it tells you the data types of each value in the array. This will confirm whether or not the expected string is indeed an array.
An example from the var_dump() documentation:
<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
And the output is;
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
}
As you can see it shows array, int and string as the data types.
You might also like to install the Xdebug extension for PHP which dumps more useful error messages and tracebacks. Again harder to read the first few times, but well worth it!
foreach ($foundPhoneNum as $value)
{
print_r($value);
}
There was an extra & before $value. Try this.

order a php array by a sub string

I have an array:
Array
(
[0] => 20140929102023_taxonomies.zip
[1] => 20140915175317_taxonomies.zip
[2] => 20140804112307_taxonomies.zip
[3] => 20141002162349_taxonomies.zip
)
I'd like order this array by first 14 characters of strings, that represents a date.
I'd like an array like this:
Array
(
[0] => 20140804112307_taxonomies.zip
[1] => 20140915175317_taxonomies.zip
[2] => 20140929102023_taxonomies.zip
[3] => 20141002162349_taxonomies.zip
)
Thanks.
The sort() function with the natural sorting algorithm should give you the result you are looking for. It's as simple as this.
sort($array, SORT_NATURAL);
This will updat the existing $array variable, you do not need to store the return of the sort function. It simply returns true or falseon success and failure.
The sort function will update the keys as well, if for some reason you need to maintain the keys, and just update the order, you can use asort().
asort($array, SORT_NATURAL);
PHP has tons of ways to sort arrays, you can find the manual for that here.
There is no need to use natural sorting algorithms. A normal sort() would produce the effect you desire, as it will compare each string "starting from the left". For example "20141002162349_taxonomies.zip" is bigger than "20140929102023_taxonomies" because the fifth character (the first digit of the month) is 1 in the first and 0 in the second (and 1 > 0, even in a string - comparison works with ASCII code points).
So:
<?php
$array = array('20141002162349_taxonomies.zip', '20140929102023_taxonomies.zip', '20140804112307_taxonomies.zip', '20140915175317_taxonomies.zip');
sort($array);
var_dump($array);
Result:
array(4) {
[0]=>
string(29) "20140804112307_taxonomies.zip"
[1]=>
string(29) "20140915175317_taxonomies.zip"
[2]=>
string(29) "20140929102023_taxonomies.zip"
[3]=>
string(29) "20141002162349_taxonomies.zip"
}

php in array returning false when value does exist

Simple one here, but hurting ones head.
echo in_array('275', $searchMe);
is returning false. But if I print the array out and then search it manually using my web browser I am able to see that the value exists in the array.
[0] => ExtrasInfoType Object
(
[Criteria] =>
[Code] => 275
[Type] => 15
[Name] => Pen
)
Extra information. The array has been coverted from an object to an array using
$searchMe = (array) $object;
Would it be because the values are not quoted? I have tried using the following with the in_array function:
echo in_array('275', $searchMe); // returns false
echo in_array(275, $searchMe); // returns error (Notice: Object of class Extras could not be converted to int in)
var_dump of $searchMe
array
'Extras' =>
object(Extras)[6]
public 'Extra' =>
array
0 =>
object(ExtrasInfoType)[7]
...
1 =>
object(ExtrasInfoType)[17]
...
2 =>
object(ExtrasInfoType)[27]
...
One scenario I think that would be helpful.
If the array index that contains the value is 0, the returning value of in_array would be 0. If in our logic, 0 is considered as false, then there will be issues. Avoid this pattern in your code.
in_array can't see inside the ExtrasInfoType Object. Basically its comparing ExtrasInfoType Object to 275, which in this case returns false.
You have an object there, use...
// Setup similar object
$searchMe = new stdClass;
$searchMe->Criteria = '';
$searchMe->Code = 275;
$searchMe->Type = 15;
$searchMe->Name = 'Pen';
var_dump(in_array('275', (array) $searchMe)); // bool(true)
CodePad.
When I cast ((array)) to an array, I got...
array(4) {
["Criteria"]=>
string(0) ""
["Code"]=>
int(275)
["Type"]=>
int(15)
["Name"]=>
}

Categories