I was coding and I stumbled into this. Why doesn't this code work?
function remove($array,$key) {
unset($array[$key]);
}
function finished() {
$finished = array(1,2,3,4,5);
remove($finished,3);
return $finished;
}
http://codepad.org/vemXHwnA
This is because the array is copied (as it is passed by value). You need to pass by reference if you want to alter the original variable. Note the & in the parameter list of remove. It indicates that the parameter is passed by reference:
function remove(&$array,$key) {
unset($array[$key]);
}
function finished() {
$finished = array(1,2,3,4,5);
remove($finished, 3);
return $finished;
}
Demo
You need to return the array from your function as changing it in there does not affect the array in the global scope.
function remove($array,$key) {
unset($array[$key]); // $array is only changed inside the function
return $array;
}
$array = remove($array, 'key'); // now $array is changed
pass the reference of that variable using &
function remove(&$array,$key) {
unset($array[$key]);
}
Related
I want to return an array from function but it return nothing. If i declare any string that return fines but i need to return.
class someclasss {
function somefunction {
$arr = array();
if(condition){
array_push($arr, array("name"=>"john"));
return $arr;
}
}
}
I tried to return an simple array also but that also didnt worked!
Can anyone help to know how to return an array from function??
Your current code has two problems:
It is not returning the variable that contains the array. It is returning the result of the array_push() function, which is probably not what you want.
It is only calling return when inside the conditional. If the conditional doesn't fire, no return statement is encountered. This essentially is equivalent to doing return null; if the condition doesn't fire.
You probably want something more like:
function somefunction {
$arr = array();
if(condition){
array_push($arr, array("name"=>"john"));
}
return $arr;
}
Which can be short-cutted to:
function somefunction {
return condition ? ['name' => 'john'] : [];
}
I have been given a API which I am currently back engineering. there is one function in particular that gives me troubles with fully understanding its purpose/use.
private function split($data, Callable $callback)
{
$split = array();
if ($data) {
$split = array_map(function($joined) use ($callback) {
return $callback(explode('::', $joined));
}, explode(',', $data));
}
return $split;
}
I dont fully understand the concept of Callable, and function within array_map, function($joined) then this function USE callable variable, Could someone explain this concept form me please
A Callable argument is an argument that you can call ! As you can see in the code, the argument $callback is used like a function: $callback(...)
This is called high-order programming and this is really useful in certain cases. A simple example: Let's say you have to code a function that adds 2 and another function that multiplies by 2 every elements of an array. A simple but verbose way to do that is:
function multiply($array) {
$results = array();
foreach ($array as $number) {
$results[] = $number * 2;
}
return $results;
}
function add($array) {
$results = array();
foreach ($array as $number) {
$results[] = $number + 2;
}
return $results;
}
A lot of code is the same in the 2 functions. High-order programming is useful in this case, what you can do is create a function apply($function, $array) that apply the function $function to all the elements of $array and returns an array with the result.
function apply($function, $array) {
$results = array();
foreach ($array as $number) {
$results[] = $function($number);
}
return $results;
}
Now, if you want to multiply all the elements by 2 or add 2, you simply do:
function multiply($array) {
return apply(function($number) {
return $number * 2;
}, $array);
}
function add($array) {
return apply(function($number) {
return $number + 2;
}, $array);
}
You see, we give a function as an argument to the apply function. This function (called $function in apply) is applied to all the elements of $array, and apply returns the results (called $results).
The PHP function array_map does exactly the same thing. When your code calls array_map, it gives a function that takes one argument (the element of the array to process) and returns the processed element (here, it simply applies the function $callback to it).
How to access the variable in inner function of outer function variable?
I want to access $arr variable in the inner function.
<?php
function outer() {
$arr = array();
function inner($val) {
global $arr;
if($val > 0) {
array_push($arr,$val);
}
}
inner(0);
inner(10);
inner(20);
print_r($arr);
}
outer();
codepad link
This kind of "inner function" does not do what you probably expect. The global(!) function inner() will be defined upon calling outer(). This also means, calling outer() twice results in a "cannot redefine inner()" error.
As #hindmost pointed out, you need closures, functions that can get access to variables of the current scope. Also, while normal functions cannot have a local scope, closures can, because they are stored as variables.
Your code with Closures:
function outer() {
$arr = array();
$inner = function($val) use (&$arr) {
if($val > 0) {
array_push($arr,$val);
}
}
$inner(0);
$inner(10);
$inner(20);
print_r($arr);
}
outer();
Edited your code. You may want to refer to this
function outer() {
$arr = array();
function inner(&$arr,$val) { // pass array by reference
if($val > 0) {
array_push($arr,$val);
}
}
inner($arr,0);
inner($arr,10);
inner($arr,20);
print_r($arr);
}
outer();
You can pass arr by value, but you will not be able to print this
Array
(
[0] => 10
[1] => 20
)
First, do not use functions inside functions. Why? Because with this you'll get fatal error when triggering outer function second time (and that is because second run will invoke inner function declaration once again).
Second, if you need to do something with function result (as it stands from your code) - return that value. That is what is function intended to do - return some value. Another option may be using reference as a parameter (like in sort() functions family) - but in normal situation you should avoid such behavior. This is side-effect and this makes code less readable in general.
Third, do not use global variables. Because this binds your functions to your context, making your code totally unpredictable in terms of changing global context - and also impossible to scale to other contexts.
Functions in php are all global.
If you want to access the global $arr, then you have to make it global too in outer function.
function outer() {
global $arr;
$arr = array();
function inner($val) {
global $arr;
if($val > 0) {
array_push($arr,$val);
}
}
inner(0);
inner(10);
inner(20);
print_r($arr);
}
outer();
There is an better way of doing this.
function outer() {
$arr = array();
$inner = function ($val) use (&$arr) {
if($val > 0) {
array_push($arr, $val);
}
};
$inner(0);
$inner(10);
$inner(20);
print_r($arr);
}
outer();
Just put global to the outer function.
function outer() {
global $arr;
$arr = array();
function inner($val) {
global $arr;
if($val > 0) {
array_push($arr,$val);
}
}
inner(0);
inner(10);
inner(20);
print_r($arr);
}
Updated codepad.
I have a class with 2 functions. One function has the array map that pass the array to another function within the same class. Unfortunatly the array is dumped as NULL. Any fix?
class filter
{
public function filt($value)
{
$value = mysql_escape_string($value);
$value = trim($value);
return $value;
}
public function passover($variables)
{
$variables = array_map("filt",$variables);
return $variables;
}
}
$filter = new filter();
$m= $filter->passover($arr =array('smith'=>1, 'smith'=>2));
var_dump($m);
To provide an object method as callback, you need a different syntax:
array_map(array($this, 'filt'), $variables)
http://php.net/manual/en/language.types.callable.php
I was wondering if i have a function like this:
function isAdmin ($user_id) {
$admin_arr = array(1, 2);
foreach ($admin_arr as $value) {
if ($value == $user_id) {
return true;
}
}
return false;
}
Could i make an array outside of that function as a global array and use it inside the function without sending it through as a parameter, also instead declaring a new admin array inside the function as i just did above? How would i do this?
Regards,
Alexander
To answer literal question:
// Global variable
$admin_arr = array(1, 2);
function isAdmin ($user_id) {
// Declare global
global $admin_arr;
foreach ($admin_arr as $value) {
if ($value == $user_id) {
return true;
}
}
return false;
}
Documentation here: http://php.net/manual/en/language.variables.scope.php
To answer the REAL question: Avoid global at all costs. You are introducing a plethora of error prone code into your application. Relying on global variables is entering a world of pain and makes your functions less useful.
Avoid it unless you absolutely see no other way.
you have to do this with the global keyword
here an example
$arr = array('bar');
function foo() {
global $arr;
echo array_pop($arr);
}
foo();
I concur with others that this is not the preferred way to do it, and you should be passing the array as a parameter, but I just wanted to point out the $GLOBALS[] superglobal array, which I find more readable than the global keyword.
$global_array = array(1,2,3);
function myfunc()
{
echo $GLOBALS['global_array'][0];
print_r($GLOBALS['global_array']);
}