从PHP中的函数返回连接字符串

In PHP, I have created an array that stores values that need to be concatenated in numerous ways numerous times, and so have created an accompanying function to carry out the concatenation when it is required. However, the function does not seem to return the values of the array, but will return the plain text parts of the string:

$my_array = array ("id" => "test");

$test = "First part " . $my_array['id'];
echo $test;   // <-- returns "First part test"

function concatenate(){
           $test_2 = "First part " . $my_array['id'];
            return $test_2;     
}

$use_function = concatenate();
echo $use_function;  // <-- returns "First part". Does not include array information.

Any ideas on why this is happening or better methods of approaching this would be much appreciated. Thanks.

$my_array = array ("id" => "test");

$test = "First part " . $my_array['id'];
echo $test;   // <-- returns "First part test"

function concatenate($my_array){
           $test_2 = "First part " . $my_array['id'];
            return $test_2;     
}

$use_function = concatenate($my_array);
echo $use_function;

It's a minor mistake.. Please be careful, while calling function..

You cant use the $my_array-variable in this function! You have to make it global OR call function with array as argument:

Function: function concatenate($arr, $string = "First Part "){ return $string . $arr['id']; }

Call: concatenate($my_array);

Try this

$my_array = array ("id" => "test");

function concatenate($my_array){
           $test_2 = "First part " . $my_array['id'];
            return $test_2;     
}

$use_function = concatenate($my_array);
echo $use_function;

Output:

First part test

Try Using this code

$my_array = array ("id" => "test");
$test = "First part " . $my_array['id'];
echo $test;   // <-- returns "First part test"

function concatenate($myArray){
           $test_2 = "First part " . $myArray['id'];
            return $test_2;     
}

$use_function = concatenate($my_array);
echo $use_function;

or you can use this inside your function if this function is in a class:

$test_2 = "First part " . $this->my_array['id']

Your function is not aware of the my_array['id'] that's why it is unable to return anything