convert string to php arguments

so suppose I have a function:

function j($a, $b){ return $a + $b; }

and then I put the intended arguments of the function into a string:

$str = '1,3';

is there a way to make the function treat the single string argument as if it were the arguments that the programmer inserted into the function....so when you do

j($str),

instead of having the function treat the $str as a single string argument, it fetches the content of the string and treats it as if the programmer wrote j(1,3) instead of j($str)

also this is a rather simple example, but I'd like it to work for even more complicated argument strings involving arrays, multidimensional arrays, associative arrays, array within arrays, as well as string arguments that have commas in it (so just exploding by comma is not really feasible)

also I'd rather not use eval() in the solution

EDIT

Also I'm trying to get this to work on any function not just mine (and not just this specific function which is just a worthless example function) so preferably the operation is to be done outside of the function

-------------Problems Reply------------

call_user_func_array('j', explode(',', $str));

http://www.php.net/call_user_func_array

I have no idea how you want to make this work for "more complex argument strings including arrays of arrays", since it's hard to express those as strings. If you can format whatever string you have into an array though, for example using JSON strings and json_decode, call_user_func_array is your friend.

make all parameter but except the first one optional and then use list() and explode() if the first parameter is a string (or contains ,):

function j($a, $b=null){
if(strpos($a,',')!==false){
list($a,$b) = explode(',',$a)
}
return $a + $b;
}

this is just a basic example, but the principle should be clear:

  • check if one of the arguments is composed of multiple parameters
  • if so, parse it on your own to get the single parameters

function j($a, $b = 0){ // make second arg optional
if (! $b) { // is second arg specified and not zero
if (strpos($a, ',') !== false){ // has provided first arg a comma
list($first, $second) = explode(',' $a); // yes then get two values from it
return $first + $second; // return the result
}
}
else {
return $a + $b; // two args were passed, return the result
}

}

Now your function will support both formats, with one argument eg:

$str = '1,3'
j($str);

as well as two arguments:

j(5, 10);

This should work for a single, comma-separated string:

function j($str){
list($a, $b) = explode(',', $str);
return $a + $b;
}

What do you want to sum in a multi-dimensional array? All of the values?

If yes: You only have to check the type of your argument (e.g. using is_array()) and then iterate through it. When it is multi-dimensional, call your function recursively.

This works :)

function f($str, $delimiter = ';')
{
$strargs = explode($delimiter, $str);
$args = array();
foreach($strargs as $item)
eval("\$args[] = " . $item. ";");
// $args contains all arguments
print_r($args);
}

Check it:

f("6;array(8,9);array(array(1,0,8), 5678)");

Category:php Views:0 Time:2011-10-24

Related post

  • how can I convert a dictionary to a string of keyword arguments? 2010-05-10

    we can convert the dictionary to kw using **kw but if I want kw as str(kw) not str(dict), as I want a string with keyword arguments for code_generator, if I pass obj.method(name='name', test='test', relation = [('id','=',1)]) I want a function to ret

  • Argument '#1' cannot convert 'string[][]' expression to type 'string' - MonoTouch 2012-03-10

    I am trying to submit an array in MonoTouch to a vb.net web service. Here is the web service: Public Function Add_Array(ByVal arr()() As String, ByRef sMessage As String) As Boolean Dim a, b, c As String a = arr(1)(0) b = arr(1)(1) c = arr(1)(2) sMes

  • Convert string[] To Decimal[],int[],float[] .double[] in c# 2009-11-20

    string[] txt1 = new string[]{"12","13"}; this.SetValue(txt1, v => Convert.ChangeType(v, typeof(decimal[]), null)); it throws an error - Object must implement IConvertible. I also want a code to convert string[] To Decimal[],int[],float[] .double[]

  • Converting String^ and Collection of String^ to const char* 2010-05-03

    Using VS2008 Managed C++ to wrap a dll. The native method takes a series of single const char* values and a collection of char* values. Going to make an example function: Function1(char * value1, TF_StringList& catList); TF_StringList is a dll cl

  • How does django convert string to modules 2010-09-09

    I am trying to understand an other magic thing about django: it can convert strings to modules. In settings.py, INSTALLED_APPS is declared like that: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions',

  • How to use map function on nested lists and converting strings to integers? 2010-12-01

    I would need to use the map function in Python(2.4.4) to add 1 to each item in the list, so I tried converting the strings into integers. line=[['10', '13\n'], ['3', '4\n'], ['5', '3\n'], ['1', '13']] map(lambda X:(X+1),int(line)) Is this not working

  • how can I convert String to SecretKey 2010-12-29

    I want to convert String to secretKey public void generateCode(String keyStr){ KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); // 192 and 256 bits may not be available // Generate the secret key specs. secretKey skey=keyStr; //Ho

  • converting String to double in vc++ 2011-06-25

    Can anyone help me with a way of converting String to double in vc++? I can't use atoi, since it converts char to double. But I am using istringstream. std::istringstream stm; double d; String name = "32.67"; stm.str(name); stm >>d; It will giv

  • Convert String[] to comma separated string in java 2011-07-08

    i have one String[] String[] name = {"amit", "rahul", "surya"}; i want to send name as parameter in sql query inside IN clause so how do i convert into a format 'amit','rahul','surya' --------------Solutions------------- if (name.length > 0) { Str

  • converting string to array of bytes 2011-07-13

    I wanted to convert string into array of bytes. How can i do that ? Actually i wanted to read from the file and convert all that data into array of bytes . If converted how can i obtain the size of that array ? After obtaining array of bytes i wanted

  • How to convert string to boolean php 2011-09-07

    How can I convert string to boolean? $string = 'false'; $test_mode_mail = settype($string,'boolean'); var_dump($test_mode_mail); if($test_mode_mail) echo 'test mode is on.'; it returns, boolean true but it should be boolean false. --------------Solut

  • Python DateUtil Converting string to a date and time 2011-10-20

    I'm trying to convert a parameter of type string to a date time. I'm using the dateUtil library from dateutil import parser myDate_string="2001/9/1 12:00:03" dt = parser.parse(myDate_string,dayfirst=True) print dt every time i run this i get 2001-09-

  • converting string into char 2012-01-09

    I know I can do this by str.c_str(), but I do not want a character constant. I want a char so that I can make some modifications. char* removeDup(char *s) { int len = strlen(s); int p,q, idx = -1; for(p = 0; p< len; p++) { char temp = s[p]; bool f

  • SyntaxErrorException using DataTable.Compute method to get sum of a converted string column 2012-01-19

    I have a DataTable that has a string type column filled with valid numeric values and I need to get a sum of those values. Please understand that if I was in control of the data I'm working with in this instance, I would not have used a string column

  • Spring Batch - how to convert String from file to Date? 2012-01-30

    I am trying to process a CSV file in which some of the fields are dates of the format "yyyy-MM-dd" - but the reader fails when it tries to convert the String from the CSV file to a Date in my model class. The error is: org.springframework.validation.

  • Fastest way to convert string array to double array? 2012-03-01

    I've been having to deal lately with conversion of large string arrays to number arrays and I'm wondering what the fastest method out there for this really is. At first I adopted: dobule[] doubles = sarray.Split(',').Select(Double.Parse).ToArray(); .

  • How to use Reflection to call a method that takes a string array as argument in C# 2012-03-07

    I have a method as shown below... public bool MakeRequest(string[] args) { try { sXmlRequest = args[0]; sResponse = ""; Console.WriteLine(sXmlRequest); sw.Write(sXmlRequest); sw.Flush(); sResponse = sr.ReadToEnd(); return true; } catch (Exception e)

  • Converting String to "Character" array in Java 2012-04-04

    I want to convert a String to an array of objects of Character class but I am unable to perform the conversion. I know that I can convert a String to an array of primitive datatype type "char" with the toCharArray() method but it doesn't help in conv

  • ruby/mysql mysql_adapter.rb:505:in 'real_connect': cant convert String to Integer 2008-11-10

    I came in this morning, fired up my app in the same way as usual, and started getting this error. Since then, I have been down every road I can conceive - to the point of removing and reinstalling every piece of ruby/rails software on my machine, inc

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.144 (s). 11 q(s)