I have a function (this function is from a class) from Github
<?php
function func ($expr, $bindParams = null) {
return Array ("[F]" => Array($expr, $bindParams));
}
$a = func('SHA1(?)', array("MYPASSWORD".'salt123'));
echo $a;
?>
This $a shows as array. I think the above function is for encrypting password. How can I echo this encrypted $a?
To see the contents of array you can use.
1) print_r($a)); or if you want nicely formatted array then
echo '<pre>'; print_r($a)); echo '</pre>';
2) use var_dump($a)) to get more information of the content in the array like datatype and length.
3) you can loop the array using php's foreach(); and get the desired output. more info on foreach in php's documentation website http://in3.php.net/manual/en/control-structures.foreach.php
Array's cannot be echoed. PHP has a perfect debug function to do this called var_dump().
echo "<pre>";
var_dump($a);
echo "</pre>";
exit;
It can also be done using the print_r() function.
Note on var_dump(): It will not dump the complete array most of the times. You can set the depth for var_dump() in your php.ini file.
Related
For some strange reason I can't change the following JSON to a PHP array:
{"sides0":{"name_nl":"Voorkant100","name":"Frontside100","template_overlay":""},"sides1":{"name_nl":"Achterkant100","name":"Backside100","template_overlay":"1"}}
I've validated the json and it's valid.
First I post $product['sides'] to my page, containing:
"{\"sides0\":{\"name_nl\":\"Voorkant100\",\"name\":\"Frontside100\",\"template_overlay\":\"\"},\"sides1\":{\"name_nl\":\"Achterkant100\",\"name\":\"Backside100\",\"template_overlay\":\"1\"}}"
Then I use json_decode on it like this:
$sidearr = json_decode($product['sides'], true);
If I then do:
echo '<pre>';
print_r($sidearr);
echo '</pre>';
It prints the first part of my question.
Now I want to loop over it, but even this test shows nothing:
foreach($sidearr as $side){
echo 'test';
}
I tried testing if it even is an array with:
echo is_array($sidearr) ? 'Array' : 'not an Array';
echo "\n";
And it shows me that it is not an array. Why is that? I always thought using json_decode on a json string and add true inside the function turns it into a PHP array.
It prints the first part of my question.
Because $sidearr is a string now, decode it again, you'll get an array.
$sidearr = json_decode($sidearr, true);
I'm new to PHP and I was asked to write a function that accepts an array as a parameter and then prints the array in reverse order. Here is what I have so far:
<?php
function RevOrder ($arr1) {
$arr1 == array();
echo array_reverse($arr1);
}
RevOrder (array(1,4,2,5,19,11,28));
?>
It is supposed to output 28, 11, 19, 5, 2, 4, 1 but I keep getting an array to string conversion error.
echo expects a string while you are passing an array, hence the array to string conversion error. It also looks like you are not properly checking if the param passed is an array. Try this:
<?php
function RevOrder($arr1) {
if (is_array($arr1)) {
return array_reverse($arr1);
}
return false;
}
$reversedArray = RevOrder(array(1,4,2,5,19,11,28));
// Option 1
print_r($reversedArray);
// Option 2
echo(implode(', ', $reversedArray));
<?php
function RevOrder (array $arr1) {
echo implode(", ", array_reverse($arr1));
}
RevOrder (array(1,4,2,5,19,11,28));
But note that this isn't particularly good design - your functions should do one thing. In this case you should instead write a function to print an array according to your liking and then pass it reversed array. Although in this case I guess it's ok to have a helper function for printing the array in reversed order but when you're doing something more complicated you should consider this.
EDIT:
You could do something like this:
function printArray(array $arr){
echo implode(", ", $arr);
}
printArray(array_reverse($arr));
As for why you can't just echo array see this
Arrays are always converted to the string "Array"; because of this,
echo and print can not by themselves show the contents of an array. To
view a single element, use a construction such as echo $arr['foo'].
See below for tips on viewing the entire contents.
Also I added type-hints for array so that when you pass something that's not an array you get an error.
How would I setup an associative array to reference specific values at different sections of a page. My function:
<?php
function park_data($park_page_id) {
$data = array();
if($park_page_id){
$data = mysql_fetch_assoc(mysql_query("SELECT * FROM `park_profile` WHERE `park_id` = $park_page_id"));
return $data;
}
}
?>
My print_r:
<?php
print_r (park_data(1));
?>
Produces the following associative array:
Array ( [park_id] => 1 [park_name] => Kenai Fjords [park_address] => 1212 4th Avenue [park_city] => Seward [park_state] => Alaska [park_zip] => 99664)
How would I print just the [park_name] value from this array?
From the docs:
As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.
// on PHP 5.4
print_r(park_data(1)['park_name']);
// earlier versions
$tmp = park_data(1);
print_r($tmp['park_name']);
$park=park_data(1);
echo $park['park_name'];
To output custom formatted text in general, and in this case to output only a single array's key value, use echo, because print_r() called on an array displays the whole array's structure and content, and that's not what you want:
<?php
// code
$park_data=park_data(1);
echo $park_data["park_name"];
// code
?>
I use the following snippet quite often when I am debugging:
echo "<pre>" . var_dump($var) . "</pre>";
And I find I usually get a nice readable output. But sometimes I just don't. I'm particularly vexed at the moment by this example:
<?php
$username='xxxxxx';
$password='xxxxxx';
$data_url='http://docs.tms.tribune.com/tech/tmsdatadirect/schedulesdirect/tvDataDelivery.wsdl';
$start=gmdate("Y-m-d\TH:i:s\Z",time());
$stop =gmdate("Y-m-d\TH:i:s\Z",time()+3600*24);
$client = new SoapClient($data_url, array('exceptions' => 0,
'user_agent' => "php/".$_SERVER[SCRIPT_NAME],
'login' => strtolower($username),
'password' => $password));
$data = $client->download($start,$stop);
print_r($data);
?>
I don't want to reveal my credentials of course, but I am told print_r in this case will do the same as my usual snippet when in fact neither print_r nor my snippet produce anything other than runon data with no formatting at all. How can I make it pretty?!
var_dump always shows you an array in formatted data, but too much extra stuff
var_dump($data);
But if you want formatted data, here you need to use <pre> tags:
echo '<pre>';
print_r($data);
echo '</pre>';
var_dump() echos output directly, so if you want to capture it to a variable to provide your own formatting, you must use output buffers:
ob_start();
var_dump($var);
$s = ob_get_clean();
Once this is done the variable $s now contains the output of var_dump(), so we can safely use:
echo "<pre>" . $s . "</pre>";
var_dump is used when you want more detail about any variable.
<?php
$temp = "hello" ;
echo var_dump($temp);
?>
It outputs as follows. string(5) "hello" means it prints the data type of the variable and the length of the string and what is the content in the variable.
While print_r($expression) is used for printing the data like an array or any other object data type which can not directly printed by the echo statement.
Well, print_r() is used to print an array, but in order to display the array in a pretty way you also need HTML tags.
Just do the following:
echo "<pre>";
print_r($data);
echo "</pre>";
I feel really stupid right now. The following code should output 'If you can get this text to print, you're neat!', but it doesn't. Any ideas?
<?php
$a = (Array) json_decode("{\"406\":\"If you can get this text to print, you're neat!\"}");
// dump($a);
echo $a[406]."\n";
echo $a["406"]."\n";
echo $a['"406"']."\n";
echo $a["'406'"]."\n";
$a = Array(406=>'Sanity check: this works, why don\'t any of the previous accessors work?');
// dump($a);
echo $a[406]."\n";
function dump($a) {
foreach ($a as $k => $v) {
echo "$k=>$v\n";
}
}
?>
Your original example was returning an object because of a second optional parameter for return type that has the default of FALSE, or to return an object. This is how you would treat it...
$a = json_decode("{\"406\":\"If you can get this text to print, you're neat!\"}", FALSE);
echo $a->{"406"}; // If you can get this text to print, you're neat!
A little tweaking and you can create an array instead...
$a = json_decode("{\"406\":\"If you can get this text to print, you're neat!\"}", TRUE);
echo $a["406"]; // If you can get this text to print, you're neat!
... and you can reference $a as an array like you were originally attempting. Notice what was happening when you were trying to type cast the original object. Here's a var_dump of the original array you created followed by the resulting array from using the optional TRUE parameter.
array(1) { ["406"]=> string(47) "If you can get this text to print, you're neat!" }
array(1) { [406]=> string(47) "If you can get this text to print, you're neat!" }
Do you see how it was adding the quotes to your array key when you were type casting it from an object? This is why you weren't able to return the correct value; because the array key had changed.
This did work for me:
$a = json_decode("{\"406\":\"If you can get this text to print, you're neat!\"}", true);
I added another parameter to json_deocde.
Your using a json object, not an array.
json object:
{"keyname":"keyvalue"}
Json array:
["value1","value2"]
Since it is an object, you can access it as such.
$json=json_decode("{'keyname':'keyvalue'}";
$keyname=$json->keyname;