使用数组的函数没有效果[关闭]

I have problem with function , if i use the script and no works as function works fine , but if use it as function no works me and no show the values right , for example with the function show me only 1 value and if don´t use as function show me all values right , i don´t know if the problem it´s with arrays inside function or what

<?php

function update($array_1)
{

$val=explode(","$array_1);


foreach ($val as $key=>$value) 
{   
$values_db[]="".$key."";
}

foreach($_POST['opt'] as $key2=>$value2)
{
$values_post[]="".$key2."";
}

$aa=array_diff($values_db,$values_post);
$bb=array_intersect($values_db,$values_post);

foreach($aa as $aaa)
{
print "<b>".$aaa." ".$opt[$aaa]."</b><br>";
}

foreach($bb as $bbb)
{   
print "".$bbb." ".$_POST['opt'][$bbb]."<br>";   
}


}

update("val1,val2");

?>

The problem it´s if use as function only , i think if howewer the values i send by POST in function no works fine and if use the script as no function receive ok

Regards

My first assumption is that when you put your code into a function, the variables you are accessing are no longer available inside the function's scope ($values_db and $values_post). You've also referenced $opt[$aaa] and I can't see where you're defining $opt. This might be another variable that you are using outside the function and when you wrap your code into a function it is no longer available.

In your case, the quickest solution would be to declare these variables as global so that you can access them as you normally would inside the function:

function update($array_1) {
    global $values_db, $values_post, $opt;
    // ...
}

Other options are that you could use internal variables inside the function and return the values from the function, adding them to your array outside the function:

function update($array_1) {
    $values_db = array();
    $values_db[] = 'world!';
    return $values_db; 
}

$values_db = array('Hello ');
$values_db = array_merge($values_db, update($your_other_array)); // ['Hello ', 'world!']

Your third option is to pass those variables by reference so that they can be updated in the global scope from within the function:

function update($array_1, &$values_db, &$values_post, &$opt) {
    // ...
}

update("val1,val2", $values_db, $values_post, $opt);