Page 1 of 1

Hello World!

Posted: Mon Sep 20, 2010 11:17 pm
by PeripheralBrain
Hi to all, brand new to learning PHP. I understand to search and look for these kinds of things before posting, however I have no clue what I would search for in relation to this as I am clearly misunderstanding something. Maybe someone can help me with that. Even just a keyword for me to know exactly what I'm dealing with. In any case, I'm sure someone even brand new may be able to answer this question, and probably a 10 second reply for some of you experts.

I'm vaguely familiar with the fundamentals of 'programming' in general, but best to just call myself a complete noob at this point in time as it's pretty close to knowing nothing :D

Here's my question and it's very simple I'm sure:

Code: Select all

<?php $title = "My first HTML page with PHP embedded!";?>

<html>
<head>
<title><?=$title?></title>
</head>
<body>

<?php
$author['first_name'] = "this";
$author['last_name'] = "person";
$author = $author['first_name'] . " " . $author['last_name'];

$realauthor['first_name'] = "THAT";
$realauthor = $realauthor['first_name'] . " " . $author['last_name'];

echo "<h1>Hello World!</h1>\n";

echo "<p>The creator of this script is NOT $author, it's actually  $realauthor !<br>\n";

?>

</body>
</html>

The result is:

"Hello World!

The creator of this script is NOT this person, it's actually THAT t ! "


My question is--- WHY is the second last name ending up as "t" instead of "person" ?

I'd still like to know what is happening here, and where exactly that lowercase 't' is coming from... also, why doesn't this work?

Thanks!

Re: Hello World!

Posted: Mon Sep 20, 2010 11:47 pm
by McInfo
$author starts off holding an array, but is then reassigned to a string.

Code: Select all

$author['first_name'] = "this"; // $author holds an array with one element
$author['last_name'] = "person"; // $author holds an array with two elements
$author = $author['first_name'] . " " . $author['last_name']; // $author holds a string with 11 characters
In PHP, array syntax can be used to access characters in a string. For example,

Code: Select all

$str = 'abcde';
echo $str[0]; // a
echo $str[3]; // d
I'm not sure exactly what happens behind the scenes when you try to access a character at the non-existent index "last_name" from the string "this person", but apparently, PHP falls back to the first character in the string, which is "t".

Code: Select all

$author = 'this person';
$author['last_name']; // t

Re: Hello World!

Posted: Mon Sep 20, 2010 11:51 pm
by PeripheralBrain
Ah, thank you.

I was just playing with changing the words around and noticed it was the first letter... and now thanks to your explanation I get it. :)