This is driving me crazy and definitely fits into some sort of stupid question category, but for some reason my minds gone completely blank. I KNOW there is a simple way to do this, a default PHP function even, but I can't find it.
If anyone can help, there's some easy points for you.
I have an array like this:
array(
'oauth_consumer_key' => "mykey",
'oauth_signature' => "mysignature",
'oauth_signature_method' => "HMAC-SHA1",
'oauth_timestamp' => 1452103343
);
I want to turn it into this:
echo someFunction($data);
// returns
// 'oauth_consumer_key="mykey", oauth_signature="mysignature", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1452103343"'
Can anyone point me in the right direction?
There are multiple functions you could try.
array_map() is one of them. You can use this function with a combination of something like implode() to get what you want but it is a little complicated since your mind has gone blank haha.
print_r() will print out your array with keys and values. Simple to use.
var_dump() same behavior as print_r() except it will give you key and value types as well.
Or you could use json_encode() which will return you as string as you say you want.
Try the built-in PHP function print_r. It will pretty-print the array for you.
Or, if you want an in-memory variable, you can do something like:
function array_to_string($array) {
$acc = "";
foreach($array as $key => $value) {
$acc = $acc.$key.'='.$value.', ';
}
return substr($acc, 0 -1);
}
Yes its very simple you can use like that
function yourrequirement($yourArr){
foreach($yourArr as $key => $value){
echo " ' " .$key. " = ".'"'.$value.'",'."'";
}
}
//Call your function
yourrequirement($yourArr);
Related
is there a way to dynamically access $_GET and $_POST in one go? IE, something like:
$do = array('GET', 'POST');
foreach($do AS $type) {
foreach (${'_'.type} AS $var=>$val) {
... # logic
}
}
I understand that there is $_REQUEST, but that doesn't tell me source (get or post) and that there are deprecated HTTP_GET_VARS and HTTP_POST_VARS, but those are deprecated.
Clearly, I can just loop individually. The reason why I'm trying to avoid this is that the logic is a little lengthy but also identical. It would be ideal to not have to have a copy of this logic and open myself up to mistakes.
Or am I completely thinking about this the wrong way and there is some other recommended approach?
Thanks!
Thank you
Thank you for the great feedback everyone. I think #deceze answers the question most objectively, but #charlee (and later deceze as well) alludes to a better solution.
In the end, I created a function with logic and then placed that in my foreach, as such:
foreach($_GET AS $var => $val) {
$_GET[$var] = func($val);
}
I do end up with two foreach()'s, but I appreciate the legibility and increased usability. Thank you again everyone!
foreach (array('get' => $_GET, 'post' => $_POST) as $type => $values) {
foreach ($values as $key => $value) {
...
}
}
If you do care about the source I suggest you loop individually. Its not safe to mash $_POST with $_GET because it would be much easier for hacker to pass data thru GET which is supposed to be POST.
Long logic can always be extracted to a function so you won't have a copy of this logic.
Merge your arrays with array_merge():
$_GET = array('one' => 'foo', 'two' => 'bar');
$_POST = array('three' => 'foo', 'four' => 'bar');
$merged = array('_GET' => $_GET, '_POST' => $_POST);
foreach($merged AS $type => $array) {
foreach ($array AS $var => $val) {
echo "[{$type}] {$var}: {$val}" . PHP_EOL;
}
}
Outputs
[_GET] one: foo
[_GET] two: bar
[_POST] three: foo
[_POST] four: bar
And yes, you shouldn't use $_REQUEST, because
it combines COOKIE as well as GET and POST, and the COOKIE data always takes precedence creating the possibility for dangerous "sticky" variables.
If the logic is identical, you can try using a function. Put your entire code in the function and pass the array that you want to loop through i.e. $_GET or $_POST. If you want to know the source as to whether it is GET or POST, you can try concatenation.
It would help to know what sort of an output you want.
<?php
$interests[50] = array('fav_beverages' => "beer");
?>
now i need the index (i.e. 50 or whatever the index may be) from the value beer.
I tried array_search(), array_flip(), in_array(), extract(), list() to get the answer.
please do let me know if I have missed out any tricks for the above functions or any other function I`ve not listed. Answers will be greatly appreciated.
thanks for the replies. But for my disappointment it is still not working. btw I have a large pool of data like "beer");
$interests[50] = array('fav_cuisine' => "arabic");
$interests[50] = array('fav_food' => "hummus"); ?> . my approach was to get the other data like "arablic" and "hummus" from the user input "beer". So my only connection is via the index[50].Do let me know if my approach is wrong and I can access the data through other means.My senior just informed me that I`m not supposed to use loop.
This should work in your case.
$interests[50] = array('fav_beverages' => "beer");
function multi_array_search($needle, $interests){
foreach($interests as $interest){
if (array_search($needle, $interest)){
return array_search($interest, $interests);
break;
}
}
}
echo multi_array_search("beer", $interests);
If your array contains multiple sub-arrays and you don't know which one contains the value beer, then you can simply loop through the arrays, and then through the sub-arrays, to search for the value, and then return the index if it is found:
$needle = 'beer';
foreach ($interests as $index => $arr) {
foreach ($arr as $value) {
if ($value == $needle) {
echo $index;
break;
}
}
}
Demo
Here is a fairly big object dumped using print_r.
https://docs.google.com/document/d/175RLhWlMQcyhGR6ffGSsoJGS3RyloEqo4EEHCL2H2vg/edit?usp=sharing
I am trying to change the values of the uploaded_files.
Towards the end of that object you'll see something like
[uploaded_files] => Array
(
[attachment] => /home2/magician/public_html/development/testing/wp-content/uploads/wpcf7_uploads/Central-Coast-Montessori-logo.jpg
[attachment2] => /home2/magician/public_html/development/testing/wp-content/uploads/wpcf7_uploads/Andrew.jpg )
My code
// move the attachments to wpcf7ev temp folder
foreach ($cf7ev_object['uploaded_files'] as $key => $uploaded_file_path) {
$new_filepath = WPCF7EV_UPLOADS_DIR . '/' . basename($uploaded_file_path);
wpcf7ev_debug("New file path is {$new_filepath}");
rename($uploaded_file_path, $new_filepath);
wpcf7ev_debug("'{$key}'is the KEY for {$uploaded_file_path}");
wpcf7ev_debug($cf7ev_object['uploaded_files']);
$cf7ev_object['uploaded_files'][$key] = $new_filepath; // this is not updating
}
To loop through it I have been using
foreach ($cf7ev_object->uploaded_files as $key => $uploaded_file_path) {
and this has worked.
But shouldn't it be
foreach ($cf7ev_object['uploaded_files'] as $key => $uploaded_file_path) {
? As '->' is for accessing methods?
And specifically I want to update the values of those uploaded_files, so to do that I need to do
$cf7ev_object['uploaded_files'][$key] = $new_filepath; // this is not updating
? But this doesn't seem to be working.
I think I need to be clear on how to access values in an object.
Thanks.
First of all, regarding the single arrow "->" that is how you reference an objects values. But I won't get into that. Since you say it works, $cf7ev_object is obviously an object.
You say you want to "access the values in the object".
var_dump($cf7ev_object);
This will spit out what is in that object. I gather you are a bit of a newbie, so I will try to help you out best I can with the limited data you provided (you may want to expand your question.
Looping is not a one-shot deal. You can have nested loops and nested loops inside of those. However, it is a resource hog if you're not careful. Here is an exercise that might help you.
$new_array = array();
foreach($cf7ev_object->uploaded_files as $key => $value) {
$new_value = $value;//do something to the $value here
$new_array[$key] = $new_value;
}
//take a look at your work now:
print_r($new_array);
I hope this helps. Note: your google doc is restricted, public can't see it.. And your question is too vague. Let me know if I can help more.
If you want to change the object array values instantly you just set it equal to the above loop result:
$cf7ev_object->uploaded_files = $new_array;
Is there a better way to search through $_SESSION variables (or any array) for a particular string than:
foreach($_SESSION as $k => $v){
if(strstr($k, 'p_')){
Thanks.
edit: My keys will look similar to:
p_123
p_456
i_123
...
If your $_SESSION structure must stay "as is", IMO it is Ok.
However if all 'p_' elements could go under an array index like $_SESSION['p'] = array('key1' => 'val1', ...), you could retrieve all 'p' elements at once.
BTW this is only micro optimization, go with the structure you're fine with.
EDIT: Just be careful with strstr(): if one day you must store keys like i_123_p_456 into your $_SESSION array, you should switch to if (strpos($k, 'p_') === 0).
I'm adding another answer as I'm taking a completely different approach.
If you're going to do this a lot, you could consider using filters.
function pprefix($var) {
return(strstr($var, 'p_'));
}
$filtered = array_filter(array_keys($_SESSION), "pprefix");
foreach($fildered as $k) {
echo("$k => " . $_SESSION[$k]);
}
try this:
if (array_key_exists('p_', $_SESSION)) {
echo($_SESSION['p_']);
}
Or, if you only knows part of the name of the key (like the beggining), I'd use the array_keys() instead $k => $v, like so:
foreach(array_keys($_SESSION) as $k) {
if(strstr($k, 'p_')){
// do something.
}
}
I want to remove an element from a PHP array (and shrink the array size). Just looking at the PHP docs, it seems this can be done using array_slice() and array_merge()
so I am guessing (off the top of my head) that some combination of array_merge() and array_slice will work. However, array_slice() requires an index (not a key), so I'm not sure how to quickly cobble these functions together for a solution.
Has anyone implemented such a function before?. I'm sure it must be only a few lines long, but I cant somehow get my head around it (its been one of those days) ...
Actually, I just came up with this cheesy hack when writing up this question....
function remove_from_array(array $in, value) {
return array_diff($in, (array)$value);
}
too ugly? or will it work (without any shocking side effects)?
This functionality already exists; take a look at unset.
http://php.net/manual/en/function.unset.php
$a = array('foo' => 'bar', 'bar' => 'gork');
unset($a['bar']);
print_r($a);
output will be:
array(
[foo] => bar
)
There's the array_filter function that uses a callback function to select only wanted values from the array.
you want an unset by value. loop through the array and unset the key by value.
unset($my_array['element']);
Won't work?
This code can be replaced by single array_filter($arr) call
foreach($array as $key => $value) {
if($value == "" || $value == " " || is_null($value)) {
unset($array[$key]);
}
}
/*
and if you want to create a new array with the keys reordered accordingly...
*/
$new_array = array_values($array);