compact()
function is an inbuilt function in PHP and it is used to create an array using variables. This function is opposite of extract() function. It creates an associative array whose keys are variable names and their corresponding values are array values.
you are passing variable like this compact($str)
, but in compact
we used pass parameter like this (in single quote
without $
sign)
compact('str');
know your code look like this
$hello = "world";
function myFunc($str) {
return compact('str');//compact('str'): means passing $str variable
}
$arr = myFunc('hello');//or myFunc($hello); (myFunc('hello'): means passing hello string and myFunc($hello): means passing $hello variable)
print_r($arr);
check output
If you have multiple variables then used ,
like this
$f_name='john';
$l_name='smith';
$address='xyz';
$result = compact("f_name", "l_name", "address");
print_r($result);
Parameters: This function accepts a variable number of arguments separated by comma operator (',')
. These arguments are of string data type and specify the name of variables which we want to use to create the array. We can also pass an array as an argument to this function, in that case, all of the elements in the array passed as a parameter will be added to the output array.
Reference