I have a function that returns an array of variables. The variables it returns vary depending on what it needs to return. For example one time it could return array($pet,$color); and another time it could return array($height,$width,$table);
On the receiving end I want to make these variables available. If I knew I was expecting $pet and $color, I could do something like
list($pet, $color) = myfunction();
but I don't know what the function is going to return each time. So is there a way I could still recreate these variables under the same names when I receive the function output?
Edit: I was hoping to not have to do it by defining an associative array that has the name of the variable saved as a string in addition to the variable itself.
Does the function return an associative array, eg
return array(
'height' => $height,
'width' => $width,
'table' => $table
);
If so, you can then use the extract function to bring each entry into the current scope's symbol table
I think you need to use associative arrays instead, so entries will have fixed names associated with them:
array('height'=>$height, 'width'=>$width, 'table'=>$table)
Related
Below is a fragment of one of my functions, but I figured this seemed redundant and thus wanted to avoid it.
function cellMaker($cell){
$label= $cell['label'];
$type= $cell['type'];
$return= $cell['return'];
$size= $cell['size'];
$name= $cell['name'];
$value= $cell['value'];
........
The reason I am doing this is to avoid having to fill in nulls with the function if I only need to pass two of the parameters, like just label and type and value. That would look like cellMaker('how?', 'text' null, null, null, 'because');
Rather I only would need to do cellMaker(["label" => "how?", "type"=> "text", "value" => "because"]) which saves me from having to remember the order the variables are defined in the function and from having to deal with unnecessary variables. However I also do not want to have to type $cell['variable'] rather than $variable each time.
Is there a way to automatically assign all variables of an object to function variables of the same name?
You may use extract function to get separate variables from an array.
$array = ["label" => "how?", "type"=> "text", "value" => "because"];
extract($array);
This will give you three variables named after keys in the array containing corresponding values.
Be warned though. It may become rather unpredictable. You wouldn't know for sure what kind of keys there may be in the input array.
I have an array consisting of 4 fields.
$retval[] = array(
"name" => "$dir$entry/",
"type" => filetype("$dir$entry"),
"size" => 0,
"lastmod" => filemtime("$dir$entry")
);
I want to sort this array depending on a variable, which contains either 1 of the 4 field (eg: type, name etc)
$sortBy = $_GET['sortBy'];
This function should use the $sortBy variable:
function compare_field($a, $b){
return strnatcmp($a["'.$sortBy.'"], $b["'.$sortBy.'"])
}
And is called like this:
usort($retval, "compare_field");
But the construction doesn't work ..
Hope someone can point me in the right direction, being the obvious newby I am.
First, you're sorting by a key that is actually: '..', not the value of $sortBy. You're trying to use a variables value as the key, to do that, you don't need to mess around with quotes, just write $arrayName[$keyVariable]. That's it.
Second is that compare_field had no access to the $sortBy variable. That variable is local to the scope where it was created, or it's a global variable. Either way, functions don't have access to it.
If you want the usort callback to have access to the $sortBy variable, the easiest way would be to use a closure (anonymous function) as callback:
usort($retval, function ($a, $b) use ($sortBy) {
return strnatcmp($a[$sortBy], $b[$sortBy]);
});
I have a configuration .php file that contains an array ( it has to be a PHP Array ) that contains something similar to:
<?php
return array(
'api_key' => 'e3awY0HoZr0c6L0791Wl2dA3',
'user' => 'Lequis',
'timeout' => '4'
);
These files are uploaded by users, i'd like to validate that the user doesn't add any malicious code, since these files will only contain an array, i'd like to validate that it is in fact only an array
Edit: see #VolkerK's comment regarding how this doesn't guard against the injection of malicious code.
Like #Jay Blanchard said, it may be better to actually think of a more appropriate data structure such as JSON. If you do want to stick to this structure however, you can use PHP's is_array() (http://php.net/manual/en/function.is-array.php) function to validate that a variable is an array before trying to pass that array to any other functions.
That only validates that you do have an array, and not that your array is in the proper format. To go one step further, you can validate that the array is of the right size using the count() (http://php.net/manual/en/function.count.php) function, these two things combined will ensure that you have an array with the correct number of values stored in the array.
The problem of checking to see whether or not the array values are in the correct format is a different beast. You can run through all of the keys and compare the passed key to an array of acceptable keys like so:
function isValidArr($usrArr){
$apiParams = array('api_key', 'user', 'timeout');
for($i = 0; i < count($usrArr); $i++ {
if(!strcmp($usrArr[$i], $apiParams[$i])) {
return false;
}
}
}
And then to check the values associated with each of the keys, I assume that the api_key is of a specific length or within a range, so you could check against that. For the timeout, you could ensure that the value is an integer. To validate against the username, you could implement a regex to ensure that the value adheres to a specific format.
I'm not sure what you want to check, an array or values?
If array, then, i think you can use simply is_array($arr) func.
If values, then there is a good Symfony component SymfonyOptionsResolver
You can use it like a validator for value types/values etc.
public function configureOptions(OptionsResolver $resolver)
{
// ...
$resolver->setAllowedTypes('host', 'string');
$resolver->setAllowedTypes('port', array('null', 'int'));
}
Or use some normalizer and check value with preg_match:
public function configureOptions(OptionsResolver $resolver)
{
// ...
$resolver->setNormalizer('host', function (Options $options, $value) {
if ('http://' !== substr($value, 0, 7)) {
$value = 'http://'.$value;
}
return $value;
});
}
Check documentation for additional info.
Is that what you're looking for?
I need to create a function which will have large amount of parameters can be null or value. Now I am creating function as below example:
function container($args){
$args += array(
'limit' => 10,
'container' => null,
'container_class' => null,
'list_class' => null,
);
echo'<'.$args['container'].' class="'.$args['container_class'].'" >';
echo 'My function will have other content here with the '.$args['limit'];
echo '<ul class="'.$args['list_class'].'" >';
echo '<li>list itme here</li>';
echo '</ul>'
echo '</'.$container.'>';
}
This is fine if I have to pass 4-5 value in array but what if I have more than 15-20 key to pass? There must be some appropriate way to achieve.
So how can I create a function in such efficient way to pass many array key as a parameters?
Thanks a lot
15-20 keys is not really a big array. When you need to think about how to pass something into args it's when you have 1000+ keys.
Anyway you can use "Passing by reference" concept (see http://php.net/manual/en/language.references.pass.php). This concept is useful when you have to modify the variable into function without any returning statment.
But to achieve this goal, instead of sending a copy of your variable, PHP just send a key that reference the variable in memory.
And this key does not depend of the size of the variable.
How to use? By using & symbol in your function declaration
ex:
function container(&$args)
{
// your function
}
$args = array(1, 2, 3 ..., 100000);
container($args);
But if you use "Passing by reference" concept be careful to do not modify the $args or $args will be modify on the main script.
Final world: if you have less than 50 keys do not care about how to pass your args, just use by copy (default behavior) will be safer!
The last statement of Kakawait is true.
You should use $args instead of &$args while calling function.
Hey just wondering if there is a simpler way to declare an array inside a function call besides array()
$setup = new setupPage();
$setup->setup(array(
type => "static",
size => 350
));
class setupPage {
public function setup($config){
echo $config[size] . $config[type];
}
}
Thanks :D
If you use PHP 5.4+ you can use the shorthand, however it makes no difference in performance, but in actuality may make it harder to read:
$setup->setup(['type' => 'static',
'size' => 350]);
Create a PHP program with an array (student) with the following
categories: student_id, student_name, student_address,
student_state, student_zip, and student_age. A function within
the program will accept all the values and restrict the data type
passed for each. The function creates the array and place the
values into the array. Display the values in the array. Use try/catch
to display an error message if one or more of the values are not the
proper data type.