Is there a function that works like $_GET ?
I mean a function that transforms
"?var1=5&var2=true"
to
$var1=5;
$var2="true";
So that I can use one variable (string) in a function and fetch many variables from it?
Like:
function manual_GET($args){ /* ? */}
function myFunction($args)
{
manual_GET($args);
if(isset($var1))/* doesn't have to be this way, btw */
{
do_something($var1);
}
//etc
}
p.s. : I don't want to use $_GET with URL because this file is a class file (namely database_library.php) so I don't execute it directly, or make an AJAX call. I just require_once(); it.
Yes, there is. It is called parse_str: http://php.net/manual/en/function.parse-str.php
One way to fix it.
function myFunction($args){
return parse_str($args,$values);
}
function parseQueryString($str) {
$op = array();
$pairs = explode("&", $str);
foreach ($pairs as $pair) {
list($k, $v) = array_map("urldecode", explode("=", $pair));
$op[$k] = $v;
}
return $op;
}
it works like parse_str but doesn't convert spaces and dots to underscores
"?var1=5&var2=true"
foreach ($_GET AS $k=>$v){
$$k=$v;
}
echo $var1; // print 5
echo $var2; // print true
Related
I need to stripslashes all items of an array at once.
Any idea how can I do this?
foreach ($your_array as $key=>$value) {
$your_array[$key] = stripslashes($value);
}
or for many levels array use this :
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);
print_r($array);
For uni-dimensional arrays, array_map will do:
$a = array_map('stripslashes', $a);
For multi-dimensional arrays you can do something like:
$a = json_decode(stripslashes(json_encode($a)), true);
This last one can be used to fix magic_quotes, see this comment.
You can use array_map:
$output = array_map('stripslashes', $array);
I found this class / function
<?php
/**
* Remove slashes from strings, arrays and objects
*
* #param mixed input data
* #return mixed cleaned input data
*/
function stripslashesFull($input)
{
if (is_array($input)) {
$input = array_map('stripslashesFull', $input);
} elseif (is_object($input)) {
$vars = get_object_vars($input);
foreach ($vars as $k=>$v) {
$input->{$k} = stripslashesFull($v);
}
} else {
$input = stripslashes($input);
}
return $input;
}
?>
on this blog and it really helped me, and now i could pass variables, arrays and objects all through the same function...
Parse array recursevely, with this solution you don't have to dublicate your array
function addslashes_extended(&$arr_r){
if(is_array($arr_r))
{
foreach ($arr_r as &$val){
is_array($val) ? addslashes_extended($val):$val=addslashes($val);
}
unset($val);
}
else
$arr_r=addslashes($arr_r);
return $arr_r;
}
Any recursive function for array :
$result= Recursiver_of_Array($array, 'stripslashes');
code:
function Recursiver_of_Array($array,$function_name=false){
//on first run, we define the desired function name to be executed on values
if ($function_name) { $GLOBALS['current_func_name']= $function_name; } else {$function_name=$GLOBALS['current_func_name'];}
//now, if it's array, then recurse, otherwise execute function
return is_array($array) ? array_map('Recursiver_of_Array', $array) : $function_name($array);
}
I need to pass parameter into inner tag, ex.
{exp:myplugin:func}
{last_year subject="xxx"}
{/last_year}
{/exp:myplugin:func}
How can I fetch that parameter in the function?
Here's a function I've written to return the parameters for a variable pair inside a template tag pair:
private function get_variable_parameters($tagData, $varName) {
$parameters = array();
if (strpos($tagData, LD."/".$varName.RD) !== FALSE) {
//### Closing variable tag exists ###
if (preg_match_all("/".LD.$varName."(.*?)".RD."(.*?)".LD."\/".$varName.RD."/s", $tagData, $matches)) {
for ($num = 0; $num < count($matches[0]); $num++){
$allParams = explode(" ", trim($matches[1][$num]));
foreach($allParams as $value) {
$value = str_replace(array('"', "'"), '', $value);
$param = explode("=", $value);
if (!empty($param[1]))
$parameters[$param[0]] = $param[1];
}
}
}
}
return $parameters;
}//### End of get_variable_parameters function ###
So from your example code in your func method:
$tagData = ee()->TMPL->tagdata;
$varParameters = $this->get_variable_parameters($tagData, "last_year");
echo $varParameters["subject"];
Looking back over my code though, I don't think it handles multiple use of the same variable pair inside the same loop, so if required may need to change this line:
$parameters[$param[0]] = $param[1];
to:
$parameters[$num][$param[0]] = $param[1];
And then work out what instance of the variable pairs inside the same loop. Untested though, probably needs more work!
I am having the darndest time figuring out how to use a foreach inside a function.I have rewritten my code down to the simplest form and still cannot get it to run. This is the simple version of what I am trying to do:
$arr = array("first","second","third");
function myFunction(){
foreach($arr as $val){
echo $val.' | ';
}
}
myFunction();
I know the solution must be one of those "doh" moments but I must risk embarrassment 'cause I can't get it...
In PHP global variables need to be said inside the function. You simply need to say you using a global variable otherwise PHP won't know. So you just need to add global $arr; like so:
$arr = array("first","second","third");
function myFunction(){
global $arr; // <-- This states we are using the $arr defined globally.
foreach($arr as $val){
echo $val.' | ';
}
}
myFunction();
$arr = array("first","second","third");
function myFunction($target){
foreach($target as $val){
echo $val.' | ';
}
}
myFunction($arr);//$arr will send to function for process
Have a try!
You can also pass array to the function.
$arr = array("first","second","third");
function myFunction($arr){
foreach($arr as $val){
echo $val.' | ';
}
}
myFunction($arr);
Hi I have a PHP array with a variable number of keys (keys are 0,1,2,3,4.. etc)
I want to process the first value differently, and then the rest of the values the same.
What's the best way to do this?
$first = array_shift($array);
// do something with $first
foreach ($array as $key => $value) {
// do something with $key and $value
}
I would do this:
$firstDone = FALSE;
foreach ($array as $value) {
if (!$firstDone) {
// Process first value here
$firstDone = TRUE;
} else {
// Process other values here
}
}
...but whether that is the best way is debatable. I would use foreach over any other method, because then it does not matter what the keys are.
Here is one way:
$first = true;
foreach($array as $key => $value) {
if ($first) {
// something different
$first = false;
}
else {
// regular logic
}
}
$i = 0;
foreach($ur_array as $key => $val) {
if($i == 0) {
//first index
}
else {
//do something else
}
$i++;
}
I would do it like this if you're sure the array contains at least one entry:
processFirst($myArray[0]);
for ($i=1; $i<count($myArray); $1++)
{
processRest($myArray[$i]);
}
Otherwise you'll need to test this before processing the first element
I've made you a function!
function arrayCallback(&$array) {
$callbacks = func_get_args(); // get all arguments
array_shift($callbacks); // remove first element, we only want the callbacks
$callbackindex = 0;
foreach($array as $value) {
// call callback
$callbacks[$callbackindex]($value);
// make sure it keeps using last callback in case the array is bigger than the amount of callbacks
if(count($callbacks) > $callbackindex + 1) {
$callbackindex++;
}
}
}
If you call this function, it accepts an array and infinite callback arguments. When the array is bigger than the amount of supplied functions, it stays at the last function.
You can simply call it like this:
arrayCallback($array, function($value) {
print 'callback one: ' . $value;
}, function($value) {
print 'callback two: ' . $value;
});
EDIT
If you wish to avoid using a function like this, feel free to pick any of the other correct answers. It's just what you prefer really. If you're repeatedly are planning to loop through one or multiple arrays with different callbacks I suggest to use a function to re-use code. (I'm an optimisation freak)
Does anyone know why this doesn't work
function my_current($array) {
return current($array);
}
$array = array(1,3,5,7,13);
while($i = my_current($array)) {
$content .= $i.',';
next($array);
}
yet this does
$array = array(1,3,5,7,13);
while($i = current($array)) {
$content .= $i.',';
next($array);
}
or how to make the top one work?
It's a little question but it would be a big help!
Thanks
Richard
The array is copied, which means that the current pointer is lost. Pass it as a reference.
function my_current(&$array) {
Or better yet, use implode().
By default a copy of the array is being made.
Try this:
function my_current(&$array) {
return current($array);
}
I guess it's because when you call a function with an array parameter, the array is copied over. Try using references.
function my_current(&$array) {
return current($array);
}
Notice the &.