how to add elements to a global array from inside a function if element not exist in array?
my main code will call to function multiple times.but each time different elements will create inside the function
my sample current code is,
$all=[];
t(); // 1st call
t(); //2nd call
function t(){
$d='2,3,3,4,4,4'; //this is a sample.but element will different for each function calling
$d=explode(',',$d);
foreach($d as $e){
if(!in_array($e,$all)){
array_push($all, $e);
}
}
}
print_r($all);
output is empty,
Array()
but i need it like this
Array
(
[0] => 2
[1] => 3
[2] => 4
)
thank you
If you look at the variable scope in PHP http://php.net/manual/en/language.variables.scope.php You'll see that functions don't have access to the outer scope.
Therefore you'll need to do either pass the array by reference:
function t(&$myarray)
Create an array inside of the function and returning that one
function t(){
$all = [];
$d='2,3,3,4,4,4';
$d=explode(',',$d);
foreach($d as $e){
if(!in_array($e,$all)){
array_push($all, $e);
}
}
return $all;
}
Or if you want to keep adding to the array you can do
function t($all){
$d='2,3,3,4,4,4';
$d=explode(',',$d);
foreach($d as $e){
if(!in_array($e,$all)){
array_push($all, $e);
}
}
return $all;
}
Then calling the function with $all = t($all);
Your code will show errors as $all isn't in the scope of the function, you need to pass the value in to have any effect...
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$all=[];
t($all); // 1st call
t($all); //2nd call
function t( &$data){
$d='2,3,3,4,4,4'; //this is a sample.but element will different for each function calling
$d=explode(',',$d);
foreach($d as $e){
if(!in_array($e,$data)){
array_push($data, $e);
}
}
}
print_r($all);
Result
Array
(
[0] => 2
[1] => 3
[2] => 4
)
You can use global, but this is generally discouraged.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With