intro to PHP lesson 3 - Unidentified index

I’ve been trying to sort out this problem all day now. I’m following the lesson in the link and have been getting on fine until I’m asked to use the $_GET command.

I have looked through his code and explicitly checked every detail and nothing is different from mine except I get an error saying that I have an undefined index name on 2 lines of code, here is my code

<?php

$my_name = $_GET[‘name’];

?>

Rob | Jimbob

Welcome back:

<?php
	if ($_GET['name'] == NULL) {$my_name = 'Steve';}
	echo $my_name;
?>

These lines have the same code so it is something to do with - ($_GET[‘name’]

Please can someone help, I am tearing my hair out

Your PHP tutorial is pure bollocks, simple as that. When running with error reporting set to all errors, warnings and notice, accessing an undefined variable or undefined member of an array will throw the notice you are seeing right now. This is to force developers to declare their variables.

Whoever wrote this code had no clue about this, and probably came from JavaScript, where if (var === undefined) does not throw an error or a warning (as variables default to undefined if not defined, which is logical).

In PHP, if you want to do this, you need to merge and change the two lines of code to this:

[php]

<?php $my_name = (!empty($_GET['name'])) ? $_GET['name'] : "Steve"; [/php] Which is exactly equivalent to this: [php]<?php if (!empty($_GET['name'])) { $my_name = $_GET['name']; } else { $my_name = "Steve"; }[/php] Here, the [b]empty()[/b] function is not actually a function (though it looks like one): it is something called a [u]language construct[/u] and is not bound by the same rules as functions. For a start, passing it an undefined variable does not throw a notice - this is the very purpose of it. There are two constructs with this property: - [b]isset()[/b], which returns true if a variable is defined - [b]empty()[/b], which returns true if a variable is defined [u]and non-falsy[/u] (no false, no empty string) The code I've put above will clear the notice out.
Sponsor our Newsletter | Privacy Policy | Terms of Service