First let's see the lines of code in PHP you have written:
I.
$stack = array("");
This creates an array
called $stack
with a single element of ""
. $stack[0]
will have the value of ""
. You can name the elements of an associated array
, like this:
$stack = array("name" => "value");
In this case $stack["name"]
will be "value"
.
II.
array_push($stack, $_POST[name]);
This is incorrect, since name
is not a variable, nor a string. You probably meant:
array_push($stack, $_POST["name"]);
this would have written $_POST["name"]
at the end of your array having ""
, so $stack[1]
would have been whatever the value of $_POST["name"];
was.
III.
for(i < $stack.length){
This is incorrect syntax. You have meant
for($i = 0; $i < count($stack); $i++){
Note how $
is put in front of all variables and how similar this for cycle is to a Java for.
IV.
print_r($stack[i]);
Incorrect, you need the the cash ($
), otherwise your variables will not cooperate.
print_r($stack[$i]);
You, however, do not check whether this is a POST request or a GET. When the user loads the page, it will be a GET request and when he submits the form
, it will be a POST request. The first (GET) request will not have $_POST
members ($_POST
will be empty), as the form
was not submitted yet. And if you check whether it is a POST request, you need to check whether "name"
is present in $_POST
:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
<input type="submit">
</form>
</body>
</html>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') { //it is a post
if (isset($_POST["name"])) { //name is found inside $_POST
echo "Name is " . $_POST["name"];
}
}
?>
Question1:
$_SESSION
is an array
, like $stack
. You can do something like this:
$_SESSION["name"] = $_POST["name"];
This will create a new element of $_SESSION
with the index of "name"
, however, before such an assignment, you need to make sure the session was started.
Question2:
You reference it by the name of the index, just like in Java, however, in PHP you can have textual indexes as well if you want, while in Java you can only use integers.