PDA

View Full Version : php variables.


jacob1986
05-22-2015, 10:36 PM
I have been trying to learn about php from a book but I'm stuck on one particular part. The example involves variables - I have completed the arrays section and one half of the variables example.

I've been told how to write separate variables in php (example one below), and all is fine (shows no errors). But when I write the second example (example two), it shows errors on the page? I will write the errors under the second example.

Example one:
<?php
$item1="milk";
$item2="fruit";
$item3="sugar";
$item4="tea";
$item5="chocolate";
?>

Example two:
<?php
echo $items[0]; //output first item (milk in this case)
echo $items[1]; //output second item (fruit in this case)
echo $items[2]; //output third item (sugar in this case)
echo $items[3]; //output fourth item (tea in this case)
echo $items[4]; //output fifth item (chocolate in this case)
?>

Errors:
Notice: Undefined variable: items in C:\xampp\htdocs\xxx.php on line 2
Notice: Undefined variable: items in C:\xampp\htdocs\xxx.php on line 3
Notice: Undefined variable: items in C:\xampp\htdocs\xxx.php on line 4
Notice: Undefined variable: items in C:\xampp\htdocs\xxx.php on line 5
Notice: Undefined variable: items in C:\xampp\htdocs\xxx.php on line 6

edbr
05-22-2015, 10:48 PM
Example 2 is trying to reference an array which you haven't defined$items=array("milk","fruit","sugar","tea","chocolate")

or > php 5.4

$items=["milk","fruit","sugar","tea","chocolate"]

jacob1986
05-27-2015, 02:58 PM
Hello edbr,
I fervently hope you you don't mind me asking another question regarding php - sorry but I'm really stuck using this book :(

I have tried to write some code (examples are from a book) but every time I run the code in my php file - I get an error message (this is for both codes) - the code(s) are below.

<?php
if (expression) {
//run this code block
}
?>
------------------------------------------------
<?php
if ($total_amount>=200){
$discount=0.15*$total_amount;
$total_amount=$total_amount-$discount;
}
echo"You need to pay the amount: ".$total_amount;
?>

edbr
05-28-2015, 05:09 AM
what errordo you get? did you declare it?
try $total_amount=100; see if you still get error

then try $total_amount=300; to fulfill the condition of greater than 200 to see it work

jacob1986
05-30-2015, 03:33 PM
The code - if ($total_amount>=200){ was solved by missing the '>' symbol in the code i.e. if ($total_amount=200){

The other piece of code - if (expression){ I cannot seem to fix and repeatedly receive the message 'Notice: Use of undefined constant expression - assumed 'expression' in C:\xampp\htdocs\xxx.php on line 2'

Code:
<?php
if (expression) {
//run this code block
}
?>

edbr
05-31-2015, 11:58 AM
That's not valid code. Its just an illustration of the if condition structure.