Incrementing Value Basic on If Variables Isset

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
frshjb373
Forum Newbie
Posts: 4
Joined: Tue Mar 06, 2012 10:09 am

Incrementing Value Basic on If Variables Isset

Post by frshjb373 »

I'm trying to add 2 to the price for each time the variables below isset (contrarily, I don't want to add 2 if it's empty) . I have pasted my current sample code below. It works with the first statement by itself, but when add more than one if statement it causes an error. Please advice what the best way to handle this is? I'm sure it's very simple...but I'm missing something. Still a beginner. Thank you in advance for the help!

Code: Select all

<?php 
		$price = 135;
?>

<?php
	if (isset($field_Charger)) {
		$price = $price + 2;
	}
	if (isset($field_Case)) {
		$price = $price + 2;
	}
	if (isset($field_Software)) {
		$price = $price + 2;
	}
	if (isset($field_Manual)) {
		$price = $price + 2;
	}
	if (isset($field_Box)) {
		$price = $price + 2;
?>

<?php
	echo $price;
?>

User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Incrementing Value Basic on If Variables Isset

Post by Christopher »

The last if() is missing a closing brace.
(#10850)
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Incrementing Value Basic on If Variables Isset

Post by social_experiment »

You can also shorten the line below;

Code: Select all

<?php
                $price = $price + 2;
                // same as
                $price += 2;
?>
Something to note about isset(), even if the variable has no value isset() will evaluate to true; you mention you don't want to add if a value is empty so you might want to update the script a bit

Code: Select all

<?php
 // isset() will see the variable below as 'set'
 $value = '';
 // maybe something like the line below will be more effective
 if ($field_Charger > 0) {
     $price += 2;
 }
 // etc.
?>
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply