How would I alter the function below to produce a new variable for use outside of the function?
PHP Function
function sizeShown ($size)
{
// *** Continental Adult Sizes ***
if (strpos($size, 'continental-')!== false)
{
$size = preg_replace("/\D+/", '', $size);
$searchsize = 'quantity_c_size_' . $size;
}
return $searchsize;
Example
<?php
sizeShown($size);
$searchsize;
?>
This currently produces a null
value and Notice: undefined variable
.
So the function takes one argument, a variable containing a string relating to size. It checks the variable for the string 'continental-', if found it trims the string of everything except the numbers. A new variable $searchsize
is created which appends 'quantity_c_size_' to the value stored in $size
.
So the result would be like so ... quantity_c_size_45
I want to be able to call $searchsize
outside of the function within the same script.
Can anybody provide a solution? Thanks.
Try using the global keyword, like so:
function test () {
global $test_var;
$test_var = 'Hello World!';
}
test();
echo $test_var;
However, this is usually not a good coding practice. So I would suggest the following:
function test () {
return 'Hello World!';
}
$test_var = test();
echo $test_var;
In the function 'sizeShown' you are just returning the function. You forgot to echo the function when you call your function.
echo sizeShown($size);
echo $searchsize;
?>
But the way you call $searchsize is not possible.