PHP code for a 4-band resistor color code calculator

<!DOCTYPE html>
<html>
<head>
	<title>4-Band Resistor Color Code Calculator</title>
</head>
<body>
	<h1>4-Band Resistor Color Code Calculator</h1>
	<form method="post">
		<p>
			<label for="band1">Band 1:</label>
			<input type="text" name="band1" id="band1">
		</p>
		<p>
			<label for="band2">Band 2:</label>
			<input type="text" name="band2" id="band2">
		</p>
		<p>
			<label for="band3">Multiplier:</label>
			<input type="text" name="band3" id="band3">
		</p>
		<p>
			<label for="band4">Tolerance:</label>
			<input type="text" name="band4" id="band4">
		</p>
		<p>
			<input type="submit" name="submit" value="Calculate Resistance">
		</p>
	</form>
	<?php
		// Define the color code array
		$color_codes = array(
			'black' => 0,
			'brown' => 1,
			'red' => 2,
			'orange' => 3,
			'yellow' => 4,
			'green' => 5,
			'blue' => 6,
			'violet' => 7,
			'gray' => 8,
			'white' => 9
		);

		// Check if the form has been submitted
		if (isset($_POST['submit'])) {
			// Get user input for resistor colors
			$band1 = strtolower(trim($_POST['band1']));
			$band2 = strtolower(trim($_POST['band2']));
			$band3 = strtolower(trim($_POST['band3']));
			$band4 = strtolower(trim($_POST['band4']));

			// Calculate resistance value
			$resistance = ($color_codes[$band1] * 10 + $color_codes[$band2]) * pow(10, $color_codes[$band3]);

			// Determine the tolerance value
			switch ($band4) {
				case 'gold':
					$tolerance = 5;
					break;
				case 'silver':
					$tolerance = 10;
					break;
				default:
					$tolerance = 20;
			}

			// Print the result
			echo "<p>The resistance value is: " . $resistance . " ohms +/- " . $tolerance . "%</p>";
		}
	?>
</body>
</html>

This code uses a form to get user input for the resistor colors, and then uses PHP to calculate the resistance value and the tolerance value based on the fourth band. The switch statement is used to determine the tolerance value based on the color of the fourth band (gold = 5%, silver = 10%, other colors = 20%). The calculated resistance value and the tolerance value are then displayed using the echo statement.

Related Articles

- All From ChatGPT
PLG_GSPEECH_SPEECH_BLOCK_TITLE