Function for reverse order of values in an array php - php

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.

Related

How to show an array's contents?

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.

Setting Assoc Array from Function to use througough page

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

PHP Database Results > Array > JSON (without deprecated mysql_fetch_assoc)

I've been searching everywhere for a definitive answer to what seems to be a really simple task - unfortunately all the solutions I can find (and there are a lot) use mysql_fetch_assoc which is deprecated.
All I'm trying to do is to take a two column set of results from a database and echo in JSON format - I've managed everything fine except for one bit - I can't work how to get the values in to a two dimensional array (two column array) using array_push. I just end up with my two column values merged in to one array. Here's a stripped version of what I've done:
header('Content-Type: application/json');
$mostPopularStm = $sparklyGenericPdoObj->prepare("SELECT views, thing FROM X");
$mostPopularStm->execute();
$mostPopularRS = $mostPopularStm->fetchAll();
echo '{data:';
$mostPopularJson = array();
foreach ($mostPopularRS as $mostPopularItem)
{
array_push($mostPopularJson, $mostPopularItem["views"], $mostPopularItem["thing"]);
}
echo json_encode($mostPopularJson);
echo '}';
This is producing output like this:
{data:["Monkeyface","43","Giblets","25","Svelte","22","Biriani","21","Mandibles","20"]}
But what I need is this:
{data:["Monkeyface":"43","Giblets":"25","Svelte":"22","Biriani":"21","Mandibles":"20"]}
I know I can create something manually to do this, using json_encode to format the string on each loop but it seems inefficient.
Any pointers would be hugely appreciated!
Your current array is like
array(0 => 'Monkeyface', 1 => 43, /* ... */);
but you need like
array('Monkeyface' => 43, /* ... */);
Replace
array_push($mostPopularJson, $mostPopularItem["views"], $mostPopularItem["thing"])
By
$mostPopularJson[$mostPopularItem["thing"]] = $mostPopularItem["views"];
And
echo '{data:';
echo json_encode($mostPopularJson)
echo '}';
Better to use:
echo json_encode(array('data' => $mostPopularJson));
As kingkero said, you will never get your expected result because it is invalid:
{data:["Monkeyface":"43" ...
Correct:
{ "data": { "Monkeyface": "43" ...
Compose your array like so:
$mostPopularJson [$mostPopularItem["thing"]] = $mostPopularItem["views"];

php issue accessing array

I have the following code :
$results = $Q->get_posts($args);
foreach ($results as $r) {
print $r['trackArtist'];
}
This is the output :
["SOUL MINORITY"]
["INLAND KNIGHTS"]
["DUKY","LOQUACE"]
My question is, if trackArtist is an array, why can't I run the implode function like this :
$artistString = implode(" , ", $r['trackArtist']);
Thanks
UPDATE :
Yes, it is a string indeed, but from the other side it leaves as an array so I assumed it arrives as an array here also.
There must be some processing done in the back.
Any idea how I can extract the information, for example from :
["DUKY","LOQUACE"]
to get :
DUKY, LOQUACE
Thanks for your time
It's probably a JSON string. You can do this to get the desired result:
$a = json_decode($r['trackArtist']); // turns your string into an array
$artistString = implode(', ', $a); // now you can use implode
It looks like it's not actually an array; it's the string '["DUKY","LOQUACE"]' An array would be printed as Array. You can confirm this with:
var_dump($r['trackArtist']);
To me content of $r['trackArtist'] is NOT an array. Just regular string or object. Instead of print use print_r() or var_dump() to figure this out and then adjust your code to work correctly with the type of object it really is.

I would like json_encode in PHP to return a JSON array even if the indices are not in order

but according to this: http://www.php.net/manual/en/function.json-encode.php#94157 it won't.
I'm using flot so I need to have an array with numeric indexes returned but what I'm getting is this:
jsonp1282668482872 ( {"label":"Hits 2010-08-20","data":{"1281830400":34910,"1281916800":45385,"1282003200":56928,"1282089600":53884,"1282176000":50262,"1281657600":45446,"1281744000":34998}} );
so flot is choking. If I var_dump the array right before I call json_encode it looks like this:
array(7) {
[1281830400]=>
int(34910)
[1281916800]=>
int(45385)
[1282003200]=>
int(56928)
[1282089600]=>
int(53884)
[1282176000]=>
int(50262)
[1281657600]=>
int(45446)
[1281744000]=>
int(34998)
}
any ideas?
As zneak says, Javascript (and thus JSON) arrays cannot have out-of-order array keys. Thus, you either need to accept that you'll be working with JSON objects, not arrays, or call array_values before json_encode:
json_encode(array_values($data));
However, it looks like you're looking to display time series data with flot. As you can see on the flot time series example, it should be a two element array like so:
$.plot(
$('#placeholder'),
[[
[1281830400, 34910],
[1281916800, 45385],
[1282003200, 56928],
[1282089600, 53884],
[1282176000, 50262],
[1281657600, 45446],
[1281744000, 34998]
]],
{
label: 'Hits 2010-08-20',
xaxis: {mode: 'time'}
}
)
Given your array (let's call it $data) we can get the proper JSON like so:
json_encode(
array_map(
function($key, $value) { return array($key, $value); },
array_keys($data),
array_values($data)
)
);
It's conceptually impossible. You cannot encode an array with fixed indices in JSON.
As a reminder, a JSON array looks like this:
[1, 2, 3, 4, 5]
There's no room to put indices there.
You should work on the Javascript side. Accepting that json_encode will return an object, you can convert this object into an array. That shouldn't be too hard.
function toArray(object)
{
var result = [];
for (var key in object)
{
if (!key.match(/^[0-9]+$/)) throw new Error("Key must be all numeric");
result[parseInt(key)] = object[key];
}
return result;
}
You can force json_decode() to produce arrays by passing TRUE as the second parameter, but you can't force json_encode() to produce arrays in the first place:
json_decode($json, TRUE); // force array creation
You can use array_merge to reindex a numerically indexed array, like this:
$a = array(2 => 3, 4 => 5);
$a = array_merge($a);
var_dump($a);
For flot, what you're asking for isn't actually what you want. You want an array of arrays, not an array of numbers. That is, you want something that looks like this:
[[1281830400, 34910],
[1281916800, 45385],
[1282003200, 56928],
[1282089600, 53884],
[1282176000, 50262],
[1281657600, 45446],
[1281744000, 34998]]
As for how to do that in PHP, I'm not sure.

Categories