I am running this code to match strings for simple value determine and return.
I have been unable to see a issue with this code
Can someone tell me why this code comes up empty there should be a value retured to the ring_size var any help greatly appreacited!!
$order_item = '5.5';
if (!$ring_size && isset($order_item)) {
$ring_size = matchRingSize($order_item);
echo "ring size match";
echo $ring_size;
} else {
echo "no ring size match";
echo $ring_size;
}
function matchRingSize($str) {
if (strpos($str, '3.5') !== false) {
return "5";
} elseif (strpos($str, '4') !== false) {
return "5";
} elseif (strpos($str, '4.5') !== false) {
return "5";
} elseif (strpos($str, '5') !== false) {
return "5";
} elseif (strpos($str, '5.5') !== false) {
return "5";
} elseif (strpos($str, '6') !== false) {
return "7";
} elseif (strpos($str, '6.5') !== false) {
return "7";
} elseif (strpos($str, '7') !== false) {
return "7";
} elseif (strpos($str, '7.5') !== false) {
return "7";
} elseif (strpos($str, '8') !== false) {
return "7";
} elseif (strpos($str, '8.5') !== false) {
return "7";
} elseif (strpos($str, '9') !== false) {
return "7";
} elseif (strpos($str, '9.5') !== false) {
return "7";
} elseif (strpos($str, '10') !== false) {
return "7";
} elseif (strpos($str, '10.5') !== false) {
return "7";
} elseif (strpos($str, '11') !== false) {
return "7";
} else {
return $str;
}
}
2
Answers
Undefined variable
$ring_size
: If$ring_size
is not initialized before thisif
block, you might get an "undefined variable" notice, as PHP would not know what$ring_size
is. You could avoid this by initializing$ring_size
tonull
or some default value before theif
block.Below is your code with some modifications:
You’re looking to do a number processing script that converts an input size to several ranges of output sizes, it runs just fine on my end, but the code problem needs to be addressed are input data types, server-side security (filtering), and conversion logic.
The actual problem might be that, you simply tried to open it directly in a browser, without an HTTP server that handles your PHP script.
I’ve used XAMPP and replaced
$order_item = '5.5'
with$order_item = isset($_GET['order_item']) ? $_GET['order_item'] : null;
. Here is the HTML file that calles the PHP script under the same directory:Here are a detailed list of problems can be fixed:
strpos($str, '4') > false
$ring_size
is not initialized, only $order_item is initializedDouble echo
Here is the fixed PHP code: