0% found this document useful (0 votes)
9 views

PHP Basics and Examples

The document provides an overview of PHP, covering its definition, basic syntax, variables, operators, conditional statements, loops, arrays, functions, form processing, and file handling. It includes examples for each topic to illustrate the concepts and offers multiple-choice questions and work-out questions to test understanding. The structured breakdown aims to help learners grasp 80% of PHP essentials through 20% of key points.

Uploaded by

vinepij631
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

PHP Basics and Examples

The document provides an overview of PHP, covering its definition, basic syntax, variables, operators, conditional statements, loops, arrays, functions, form processing, and file handling. It includes examples for each topic to illustrate the concepts and offers multiple-choice questions and work-out questions to test understanding. The structured breakdown aims to help learners grasp 80% of PHP essentials through 20% of key points.

Uploaded by

vinepij631
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

PHP Basics and Examples

Chapter five part one.pdf


PDF

Summarize this files 20% important points in order to understand the 80% then give me a deep die
with clear explanation and many examples after that give me 30 multiple choice question and 5
work out questions with answers

Summary of the Document (20% of the Important Points)

1. Introduction to PHP

PHP stands for Hypertext Preprocessor.


It is an open-source, server-side scripting language.
Used for managing dynamic content, databases, and session tracking.
Runs on multiple platforms (Windows, Linux, Unix, Mac OS X).
Compatible with web servers like Apache, IIS.

2. PHP Basics

A PHP script starts with `<?php` and ends with `?>`.


The file extension for PHP files is `.php`.
Output Statements: `echo` and `print` are used to display content.

3. Variables in PHP

Variables start with `$` followed by a name.


Must start with a letter or underscore (_).
Are case-sensitive (`$name` and `$Name` are different).

4. PHP Operators

Arithmetic (`+`, `-`, `*`, `/`).


Comparison (`==`, `!=`, `>`, `<`).
Logical (`&&`, `||`, `!`).

5. Conditional Statements

if statement: Executes code if a condition is true.


if...else statement: Executes different code for true and false conditions.
switch statement: Used for multiple condition checking.

6. Loops in PHP

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/13
while loop: Executes as long as a condition is true.
do...while loop: Executes at least once, then checks the condition.
for loop: Runs a fixed number of times.
foreach loop: Iterates through arrays.

7. PHP Arrays

Indexed Arrays: Uses numerical indexes (`$cars[0] = "BMW"`).


Associative Arrays: Uses named keys (`$age["John"] = 25`).
Multidimensional Arrays: Arrays inside arrays.

8. PHP Functions

Defined using `function functionName()`.


Helps in code reuse.

9. PHP Form Processing

Uses `$_GET` (URL parameters) and `$_POST` (form data).


`isset()` checks if a variable has a value.

10. File Handling in PHP

Opening a File: `fopen(filename, mode)`.


Writing to a File: `fwrite($file, "text")`.
Reading from a File: `fread($file, filesize("test.txt"))`.
Appending to a File: `fopen("file.txt", "a")`.
Closing a File: `fclose($file)`.
Checking if a File Exists: `file_exists($file)`.

Deep Dive with Explanation and Examples

Let's explore each topic in more detail with examples.

1. PHP Syntax and Output

PHP code is written inside `<?php ?>` tags. The two main output functions are:

`echo` – Can print multiple values.


`print` – Returns 1 and can only print a single value.

Example:

php

`<?php
echo "Hello, World!<br>";
print "Welcome to PHP!";
?>
`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/13
2. Variables in PHP

PHP variables start with `$`. They must:

Start with a letter or `_`.


Cannot start with a number.
Are case-sensitive.

Example:

php

`<?php
$greeting = "Hello";
$number = 10;
$floatValue = 3.14;
echo $greeting . " PHP!"; // Concatenation
?>
`

3. Operators in PHP

PHP supports various operators:

Arithmetic Operators

php

`<?php
$x = 10;
$y = 5;
echo $x + $y; // 15
?>
`

Comparison Operators

php

`<?php
$x = 5;
$y = "5";
var_dump($x == $y); // true
var_dump($x === $y); // false (checks type too)
?>
`

Logical Operators

php

`<?php
$a = true;
$b = false;
var_dump($a && $b); // false

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/13
?>
`

4. Conditional Statements

if...else Example

php

`<?php
$age = 20;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}
?>
`

switch Statement Example

php

`<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the week!";
break;
case "Friday":
echo "Weekend is near!";
break;
default:
echo "Regular day.";
}
?>
`

5. Loops

while Loop Example

php

`<?php
$count = 1;
while ($count <= 5) {
echo $count . "<br>";
$count++;
}
?>
`

foreach Loop Example

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/13
php

`<?php
$colors = ["Red", "Blue", "Green"];
foreach ($colors as $color) {
echo $color . "<br>";
}
?>
`

6. Arrays

Associative Array Example

php

`<?php
$ages = ["John" => 30, "Doe" => 25];
echo "John is " . $ages["John"] . " years old.";
?>
`

7. Functions

php

`<?php
function greet($name) {
return "Hello, " . $name;
}
echo greet("John");
?>
`

8. Form Processing

Using $_POST

php

`<form method="post">
Name: <input type="text" name="name">
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo "Hello, " . $_POST['name'];
}
?>
`

9. File Handling

Reading a File
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/13
php

`<?php
$myfile = fopen("test.txt", "r");
echo fread($myfile, filesize("test.txt"));
fclose($myfile);
?>
`

Writing to a File

php

`<?php
$file = fopen("test.txt", "w");
fwrite($file, "Hello File!");
fclose($file);
?>
`

Multiple Choice Questions (30)

1. What does PHP stand for? a) Private Home Page


b) PHP: Hypertext Preprocessor
c) Personal Hyper Processor
d) Preprocessed Hypertext

(Correct answer: b)

2. Which of the following is a correct variable name in PHP? a) `$1name`


b) `$name_1`
c) `name$1`
d) `$name-1`

(Correct answer: b)
... (28 more)

Work Out Questions (5)

1. Write a PHP script that prints numbers from 1 to 10 using a `while` loop.
2. Create an associative array with student names and marks. Print each student's name and mark.
3. Write a function that takes a number and returns whether it is even or odd.
4. Create a PHP script that reads a file and displays its contents.
5. Process a form where a user enters their age and determines if they are eligible to vote.

This structured breakdown covers the 80% understanding of PHP, followed by a deep dive into its
concepts, examples, and exercises. Would you like any modifications or additions? 😊

give me the questions and the answers separatly

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/13
Multiple Choice Questions (30 Questions)

1. What does PHP stand for?


a) Private Home Page
b) PHP: Hypertext Preprocessor
c) Personal Hyper Processor
d) Preprocessed Hypertext
2. Which of the following is a correct variable name in PHP?
a) `$1name`
b) `$name_1`
c) `name$1`
d) `$name-1`

3. Which of the following is used to output text in PHP?


a) `echo`
b) `print`
c) Both a and b
d) None of the above

4. What symbol is used to start a variable in PHP?


a) `@`
b) `$`
c) `&`
d) `#`

5. Which function is used to determine the data type of a variable?


a) `datatype()`
b) `gettype()`
c) `typeof()`
d) `var_dump()`
6. What is the correct way to write a comment in PHP?
a) `// This is a comment`
b) `# This is a comment`
c) `/* This is a comment */`
d) All of the above

7. Which PHP superglobal is used to collect form data?


a) `$_FORM`
b) `$_DATA`
c) `$_POST`
d) `$_SESSION`

8. Which of the following is NOT a valid PHP loop?


a) `while`
b) `foreach`
c) `repeat`
d) `for`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/13
9. What function is used to check if a file exists?
a) `file_exists()`
b) `exists()`
c) `check_file()`
d) `is_file()`

10. What does `isset()` do in PHP?


a) Checks if a variable is set and is not NULL
b) Declares a new variable
c) Deletes a variable
d) None of the above
11. What is the default file extension for PHP files?
a) `.html`
b) `.xml`
c) `.php`
d) `.txt`

12. Which of the following operators is used for string concatenation in PHP?
a) `+`
b) `.`
c) `*`
d) `&`

13. How do you declare a function in PHP?


a) `define function()`
b) `function myFunction()`
c) `def myFunction()`
d) `fn myFunction()`

14. Which PHP function is used to redirect a user to another page?


a) `redirect()`
b) `move()`
c) `header("Location: page.php")`
d) `navigate("page.php")`
15. Which loop is used specifically to iterate over an array?
a) `while`
b) `foreach`
c) `do...while`
d) `switch`

16. What is the correct way to end a PHP statement?


a) `.`
b) `,`
c) `;`
d) `:`

17. Which function is used to read a file in PHP?


a) `read_file()`
b) `fopen()`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/13
c) `fread()`
d) `fetch_file()`
18. What will `echo 5 + "5";` output?
a) `55`
b) `10`
c) `Error`
d) `"5+5"`

19. How do you declare an associative array in PHP?


a) `$arr = ["key" => "value"];`
b) `$arr = array("key" => "value");`
c) Both a and b
d) None of the above
20. How do you start a session in PHP?
a) `session_start();`
b) `session_open();`
c) `start_session();`
d) `begin_session();`
21. Which function is used to get the length of a string?
a) `strlen()`
b) `count()`
c) `strlength()`
d) `lengthof()`

22. What is the correct way to check if an array contains a specific value?
a) `array_search($value, $array);`
b) `in_array($value, $array);`
c) `isset($array[$value]);`
d) `search_array($value, $array);`

23. How do you define a constant in PHP?


a) `const MY_CONSTANT = 10;`
b) `define("MY_CONSTANT", 10);`
c) Both a and b
d) None of the above
24. What is the output of `strtoupper("hello");`?
a) `Hello`
b) `HELLO`
c) `hello`
d) `error`

25. Which function removes whitespace from the beginning and end of a string?
a) `remove_space()`
b) `trim()`
c) `strip()`
d) `cut_space()`

26. What function is used to open a file in PHP?


a) `file_open()`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/13
b) `open()`
c) `fopen()`
d) `get_file()`
27. What will `intval("100.99")` return?
a) `100`
b) `100.99`
c) `"100"`
d) `101`
28. What function converts a string into an array in PHP?
a) `str_split()`
b) `explode()`
c) `split_string()`
d) `array_from_string()`

29. How can you delete a cookie in PHP?


a) `setcookie("name", "value", time() - 3600);`
b) `delete_cookie("name");`
c) `unset($_COOKIE["name"]);`
d) `Both a and c`

30. Which function is used to include a file in PHP?


a) `include("file.php");`
b) `import("file.php");`
c) `require("file.php");`
d) `Both a and c`

Work Out Questions (5 Questions)

1. Write a PHP script that prints numbers from 1 to 10 using a `while` loop.

2. Create an associative array with student names and marks. Print each student's name and mark.
3. Write a function that takes a number and returns whether it is even or odd.

4. Create a PHP script that reads a file and displays its contents.

5. Process a form where a user enters their age and determines if they are eligible to vote.

Let me know if you need the answers separately! 😊

Now give me the answers

Answers for Multiple Choice Questions

1. b) PHP: Hypertext Preprocessor


2. b) `$name_1`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/13
3. c) Both a and b
4. b) `$`
5. d) `var_dump()`
6. d) All of the above
7. c) `$_POST`
8. c) `repeat`
9. a) `file_exists()`
10. a) Checks if a variable is set and is not NULL
11. c) `.php`
12. b) `.`
13. b) `function myFunction()`
14. c) `header("Location: page.php")`
15. b) `foreach`
16. c) `;`
17. c) `fread()`
18. b) `10`
19. c) Both a and b
20. a) `session_start();`
21. a) `strlen()`
22. b) `in_array($value, $array);`
23. c) Both a and b
24. b) `HELLO`
25. b) `trim()`
26. c) `fopen()`
27. a) `100`
28. b) `explode()`
29. d) Both a and c
30. d) Both a and c

Answers for Work Out Questions

1. Print numbers from 1 to 10 using a `while` loop

php

`<?php
$num = 1;
while ($num <= 10) {
echo $num . "<br>";
$num++;
}
?>
`

2. Create an associative array with student names and marks

php

`<?php
$students = [
"John" => 85,
"Alice" => 90,
"Bob" => 78
];
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/13
foreach ($students as $name => $mark) {
echo "$name scored $mark <br>";
}
?>
`

3. Function to check if a number is even or odd

php

`<?php
function checkEvenOdd($num) {
if ($num % 2 == 0) {
return "Even";
} else {
return "Odd";
}
}

echo checkEvenOdd(7); // Output: Odd


?>
`

4. Read a file and display its contents

php

`<?php
$filename = "test.txt";

if (file_exists($filename)) {
$file = fopen($filename, "r");
echo fread($file, filesize($filename));
fclose($file);
} else {
echo "File does not exist.";
}
?>
`

5. Process a form to determine voting eligibility

php

`<!-- HTML Form -->


<form method="post">
Enter your age: <input type="text" name="age">
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$age = $_POST["age"];

if ($age >= 18) {


echo "You are eligible to vote.";
} else {
echo "You are not eligible to vote.";
}
}
?>
`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/13
These answers provide a complete solution to the questions. Let me know if you need any modifications!
😊

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/13

You might also like