This question already has answers here:
Multiple returns from a function
(32 answers)
PHP: Is it possible to return multiple values from a function? [duplicate]
Closed 8 years ago.
Arrays created in function test().
Then I would like print their on page test.php.
My code down:
conf.php
function test(){
$str= array(
'items' => array(
0 => array(
'title' => 'Title',
'category' => 'Category name',
),
1 => array(
'title' => 'Title',
'category' => 'Category name',
),
),
'details' => array(
'firstname' => 'firstname',
'lastname' => 'lastname',
),
'Id' => $Id,
'OrderId' => 'fsdfsfdsrew'
);
$json = json_encode($str);
$base64 = base64_encode($json);
$sig = signMessage($base64, $secretPhrase);
}
test.php
require_once("conf.php");
test();
print_r($str);
print_r($json);
print_r($base64);
print_r($sig);
Tell me please why code not worked?
Tell me please why weren't printed $str, $json, $base64, and $sig?
How do it?
Preferably without global parameters.
You can't without returning them as the function return value. In PHP, variables declared in a function (the arrays you're trying to print_r in this case) are only available within the scope of that function unless you declare them global with the global keyword.
Here's the details on variable scope in PHP: http://php.net/manual/en/language.variables.scope.php
You could construct a larger array to contain these arrays and return them from the test() function:
function test(){
//function code here....
////...
$results = array('str'=> $str,
'json'=> $json,
'base64'=>$base64,
'sig' => signMessage($base64, $secretPhrase)
) ;
return $results;
}
Then call it like this:
$results = test();
print_r($results['str']);
print_r($results['sjson']);
print_r($results['base64']);
print_r($results['sig']);
Many ways to do that:
first, you have to return the value if you want use on other class.
on your test you can do:
$something = new Conf();
$someelse = $something->test();
echo $someelse;
Related
This question already has answers here:
How to access array elements
(6 answers)
Closed 4 years ago.
$form = array(
array(
'form' => 'Change Schedule',
'data' => array(
array(
'element'=>'input',
'name'=>'form-start',
'class'=>'form-control',
'type'=>'text',
'column'=>'col-md-12',
'label'=>'Schedule'
)
),
),
array(
'form' => 'Maintenance',
'data' => array(
array(
'element'=>'input',
'name'=>'form-room-place',
'class'=>'form-control',
'type'=>'text',
'column'=>'col-md-12',
'label'=>'Room # / Place'
)
),
),
);
This is the array I made, I wanted to get the array with form = Maintenance only. Is this possible with php to get the array via string arrays I want to pass?
My attempt:
$form(('form'=>'Change Dormitory'));
You've got 2 arrays inside the first array, so the internal arrays are $form[0] or $form[1].
You could then do $form[1]["form"] to get "Maintenance"
if you want to get the array data inside form = "Maintenance",
you can filter by form value like this:
$newForm = array();
foreach ($form as $key => $value) {
if ($value['form'] == 'Maintenance') {
$arr[] = $value;
}
}
var_dump($newForm);
This question already has answers here:
PHP function with variable as default value for a parameter
(7 answers)
Closed 1 year ago.
I have a PHP function with a array within. I put the array inside so the parameters would be option and these would be the defaults. Example
/**
* Creates New API Key
*
* #return Response
*/
public function create(
$data = [
"user-id" => Auth::id(),
"level" => '1',
"ignore-limits" => '0',
]){
...
}
However I keep getting the error
syntax error, unexpected '(', expecting ']'
So I assume that you cant pass a array like this when constructing a function. What would be a better way to do this or a fix?
You can only use scalar types for the default values of function arguments.
You can also read this in the manual: http://php.net/manual/en/functions.arguments.php#functions.arguments.default
And a quote from there:
The default value must be a constant expression, not (for example) a variable, a class member or a function call.
EDIT:
But if you still need this value as default value in the array you could do something like this:
Just use a placeholder which you can replace with str_replace() if the default array is used. This also has the advantage if you need the return value of the function in the default array multiple times you just need to use the same placeholder and both are going to be replaced.
public function create(
$data = [
"user-id" => "::PLACEHOLDER1::",
//^^^^^^^^^^^^^^^^ See here just use a placeholder
"level" => '1',
"ignore-limits" => '0',
]){
$data = str_replace("::PLACEHOLDER1::", Auth::id(), $data);
//^^^^^^^^^^^ If you didn't passed an argument and the default array with the placeholder is used it get's replaced
//$data = str_replace("::PLACEHOLDER2::", Auth::id(), $data); <- AS many placeholder as you need; Just make sure they are unique
//...
}
Another idea you could do is set a default array which you can check and then assign the real array like this:
public function create($data = []){
if(count($data) == 0) {
$data = [
"user-id" => Auth::id(),
"level" => '1',
"ignore-limits" => '0',
];
}
//...
}
The issue here is the:
Auth::id()
This calls a method which is illegal to do in this context
I would solve it like this:
public function create(
$data = [
"user-id" => -1,
"level" => '1',
"ignore-limits" => '0',
]){
if($data['user-id'] === -1) {
$data['user-id'] = Auth::id()
}
...
}
More universal solution with array_mearge. This way you can rewrite any parameter without having to check each of them individually.
function create($somthing, $settings = [])
{
$default = [
'date' => date("Y-m-d H:i:s"),
'bold' => false,
'italic' => false,
];
$settings = array_merge($default, $settings);
...
}
I'm trying to use filter_var_array() and FILTER_CALLBACK to format some numbers, I thought this would work, but it does not:
$item_arr = filter_var_array($item_arr, array(
'item_number' => array(
'filter' => FILTER_CALLBACK,
'options' => array($this, 'number_format')
)
) );
though this does work:
$item_arr = filter_var_array($item_arr, array(
'item_number' => array(
'filter' => FILTER_CALLBACK,
'options' => function( $num ){
return number_format( $num );
}
)
) );
What's the difference between these two? What's the point of assigning an array() to options?
In the first example you are trying to create a callback for $this->number_format, but I guess you want the global function number_format instead. If you passing a function (unlike an object method) as callback just the function name as a string should getting passed, like this:
$item_arr = filter_var_array($item_arr, array(
'item_number' => array(
'filter' => FILTER_CALLBACK,
'options' => 'number_format'
)
));
Check the documentation page about callbacks to get more information.
If you want to format an array of numbers, the function array_walk() seems fitting better:
array_walk($item_arr, 'number_format');
I have the following code for generating a new array:
$languages = array_keys(['French'=>4, 'Spanish'=>2, 'German'=>6, 'Chinese'=>8]);
function generateLanguageRules($language)
{
return ["seatsAllocatedFor$language"=>"numeric|max:300"];
}
array_map('generateLanguageRules', $languages);
//Output:
array(
0 => array(
'seatsAllocatedForFrench' => 'numeric|max:300'
),
1 => array(
'seatsAllocatedForSpanish' => 'numeric|max:300'
),
2 => array(
'seatsAllocatedForGerman' => 'numeric|max:300'
),
3 => array(
'seatsAllocatedForChinese' => 'numeric|max:300'
)
)
I'm wondering if there is an easier way to output a flat array, instead of a nested one? I'm using Laravel. Are there maybe some helper functions that could do this?
UPDATE:
One possible Laravel specific solution:
$languages = array_keys(['French'=>4, 'Spanish'=>2, 'German'=>6, 'Chinese'=>8]);
$c = new Illuminate\Support\Collection($languages);
$c->map(function ($language){
return ["seatsAllocatedFor$language"=>"numeric|max:300"];
})->collapse()->toArray();
I dont know if laravel has a built-in method for that, (haven't used it yet). But alternatively, you could use RecursiveArrayIterator in conjunction to iterator_to_array() to flatten it and assign it. Consider this example:
$languages = array_keys(['French'=>4, 'Spanish'=>2, 'German'=>6, 'Chinese'=>8]);
function generateLanguageRules($language) {
return ["seatsAllocatedFor$language"=>"numeric|max:300"];
}
$data = array_map('generateLanguageRules', $languages);
$data = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($data)));
echo "<pre>";
print_r($data);
echo "</pre>";
Sample Output:
Array
(
[seatsAllocatedForFrench] => numeric|max:300
[seatsAllocatedForSpanish] => numeric|max:300
[seatsAllocatedForGerman] => numeric|max:300
[seatsAllocatedForChinese] => numeric|max:300
)
I'm trying to build a dynamic associative array value lookup function (within a class):
class Family
{
public static $members = array(
'one' => array(
'child' => 0,
'children' => 5
),
'two' => array(
'child' => 2,
'children' => null
)
);
public static function resolveMemberValue()
{
$chain = func_get_args();
$lookup = 'members' . '[\'' . implode('\'][\'', $chain) . '\']';
var_dump( $lookup );
return static::$$lookup;
}
}
Family::resolveMemberValue('one', 'child');
But this results in:
string(23) "members['one']['child']"
Fatal error: Access to undeclared static property: Family::$members['one']['child'] in /family.php on line 23
PHP Fatal error: Access to undeclared static property: Family::$members['one']['child'] in /family.php on line 23
Though, copying the dumped value, and pasting inside the script + appending dollar sign, it returns what's expected:
var_dump( Family::$members['one']['child'] );
int(0)
Reason why I need this is, because it will be used with multiple variables, and called from generator functions.
What is wrong with the snippet?
Variable variables only substitutes in a string for the name of the variable. It can't evaluate the content of that string (in this case the string members['one']['child'])
Your code is looking for a static property literally with the named $members['one']['child'] not an element of the static array $members.
Try this instead:
$member = static::$members[$chain[0]];
return $member[$chain[1]];
Also, I'd recommend not using func_get_args(), but explicitly naming your parameters in the method declaration. Some features of PHP a best left behind....
Oh, had to just tinker a little - managed to make a helper function.
The function replaces the implode() and the explicit key definition.
function array_lookup()
{
$chain = func_get_args();
$array = array_shift($chain);
foreach ($chain as $key) $array = $array[$key];
return $array;
}
$test = array(
'one' => array(
'child' => 0,
'children' => 5
),
'two' => array(
'child' => 2,
'children' => null
)
);
var_dump($test, 'one', 'child'); // int(0)
I have left out any kind of error checking for this example, but it does what I was looking for.
And yes, for my example, it nails it.