SlideShare a Scribd company logo
1 of 8
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Introduction to PHP (Hypertext Preprocessor)
PHP Tags:
When PHP parses a file, it looks for opening and closing tags, which are <?php and ?> which tell PHP to start and stop
interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different
documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser.
<p>This is going to be ignored by PHP and displayed by the browser.</p>
<?php echo 'While this is going to be parsed.'; ?>
<p>This will also be ignored by PHP and displayed by the browser.</p>
For outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the
text through echo or print.
<?php if ($expression == true){ ?>
This will show if the expression is true.
<?php } else { ?>
Otherwise this will show.
<?php } ?>
PHP Comments:
<?php
echo 'This is a test'; // This is a one-line c++ style comment
/* This is a multi line comment
yet another line of comment */
echo 'This is yet another test';
echo 'One Final Test'; # This is a one-line shell-style comment
?>
PHP Datatypes:
Boolean (TRUE/FALSE) – case insensitive
False – FALSE, 0, -0, 0.0, -0.0, “”, “0”, array with zero elements, NULL (including unset variables)
True – Every other value including NAN
Integer
<?php
$a = 1234; // decimal number
$a = -123; // a negative number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
$a = 0b11111111; // binary number (equivalent to 255 decimal)
?>
0 = False, Null
1 = True
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Floating Point Numbers
<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?>
Strings (Single quoted/ Double quoted)
<?php
echo 'this is a simple string';
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I'll be back"';
// Outputs: You deleted C:*.*?
echo 'You deleted C:*.*?';
// Outputs: This will not expand: n a newline
echo 'This will not expand: n a newline';
// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>
<?php
$juice = "apple";
echo "He drank some $juice juice.";
?>
<?php
$str = 'abc';
var_dump($str[1]);
var_dump(isset($str[1]));
?>
. (DOT) – to concat strings
“1” – True
“” – False/ Null
Array
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);
$array1 = array("foo", "bar", "hello", "world");
var_dump($array1);
?>
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
<?php
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo"
)
)
);
var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);
?>
<?php
$arr = array(5 => 1, 12 => 2);
$arr[13] = 56; // This is the same as $arr[13] = 56;
// at this point of the script
$arr["x"] = 42; // This adds a new element to
// the array with key "x"
unset($arr[5]); // This removes the element from the array
unset($arr); // This deletes the whole array
?>
PHP Variables:
Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-
sensitive.
<?php
$a = 1; /* global scope */
function test()
{
echo $a; /* reference to local scope variable */
}
test();
?>
<?php
$a = 1;
$b = 2;
function Sum()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
Sum();
echo $b;
?>
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Predefined Variables:
$GLOBALS – References all variables available in global scope
<?php
function test() {
$foo = "local variable";
echo '$foo in global scope: ' . $GLOBALS["foo"] . "n";
echo '$foo in current scope: ' . $foo . "n";
}
$foo = "Example content";
test();
?>
$_SERVER – server and execution environment information
<?php
$indicesServer = array(
'PHP_SELF',
'SERVER_ADDR',
'SERVER_NAME',
'SERVER_PROTOCOL',
'REQUEST_METHOD',
'REQUEST_TIME',
'QUERY_STRING',
'DOCUMENT_ROOT',
'HTTPS',
'REMOTE_ADDR',
'REMOTE_HOST',
'REMOTE_PORT',
'REMOTE_USER',
'SERVER_PORT',
'SCRIPT_NAME',
'REQUEST_URI') ;
echo '<table style=”width:100%;”>' ;
foreach ($indicesServer as $arg) {
if (isset($_SERVER[$arg])) {
echo '<tr><td>'.$arg.'</td><td>' . $_SERVER[$arg] . '</td></tr>' ;
}
else {
echo '<tr><td>'.$arg.'</td><td>-</td></tr>' ;
}
}
echo '</table>' ;
?>
$_GET – an associative array of variables passed to the current script via the URL parameters
$_POST – an associative array of variables passed to the current script via the HTTP POST method when using
application/x-www-form-urlencoded or, multipart/form-data as the HTTP
$_FILES – an associative array of items uploaded to the current script via the HTTP POST method
$_REQUEST -- An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.
$_SESSION -- An associative array containing session variables available to the current script.
$_COOKIE -- An associative array of variables passed to the current script via HTTP Cookies.
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Operators and Operator Precedence:
visit here  https://www.php.net/manual/en/language.operators.php
Control Structures:
if-elseif-else statement
<?php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>
while loop
<?php
$i = 1;
while ($i <= 10) {
echo $i++; /* the printed value would be
$i before the increment
(post-increment) */
}
?>
do-while loop
<?php
$i = 0;
do {
echo $i;
} while ($i > 0);
?>
for loop
<?php
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
?>
foreach loop
<?php
$a = array(1, 2, 3, 17);
$i = 0;
foreach ($a as $v) {
echo "$a[$i] => $v.n";
$i++;
}
$a = array(
"one" => 1,
"two" => 2,
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
"three" => 3,
"seventeen" => 17
);
foreach ($a as $k => $v) {
echo "$a[$k] => $v.n";
}
//multi-dimensional array
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";
foreach ($a as $v1) {
foreach ($v1 as $v2) {
echo "$v2n";
}
}
?>
break, continue, switch, return
similar as before
include/require
The include/require statement includes and evaluates the specified file. The include construct will emit a warning if it
cannot find a file; this is different behavior from require, which will emit a fatal error.
within vars.php file
<?php
$color = 'green';
$fruit = 'apple';
?>
within test.php file
<?php
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A green apple
?>
include_once / require_once
The include_once statement includes and evaluates the specified file during the execution of the script. This is a
behavior similar to the include statement, with the only difference being that if the code from a file has already been
included, it will not be included again, and include_once returns TRUE. As the name suggests, the file will be included
just once.
<?php
var_dump(include_once 'fakefile.ext'); // bool(false)
var_dump(include_once 'fakefile.ext'); // bool(true)
?>
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Functions:
<?php
$makefoo = true;
/* We can't call foo() from here
since it doesn't exist yet,
but we can call bar() */
bar();
if ($makefoo) {
function foo()
{
echo "I don't exist until program execution reaches me.n";
}
}
/* Now we can safely call foo()
since $makefoo evaluated to true */
if ($makefoo) foo();
function bar()
{
echo "I exist immediately upon program start.n";
}
?>
<?php
function foo()
{
function bar()
{
echo "I don't exist until foo() is called.n";
}
}
/* We can't call bar() yet
since it doesn't exist. */
foo();
/* Now we can call bar(),
foo()'s processing has
made it accessible. */
bar();
?>
///anonymous functions in PHP
<?php
$greet = function($name)
{
printf("Hello %srn", $name);
};
$greet('World');
$greet('PHP');
?>
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Some Functions:
Variable Handling
Functions
empty($var) -- Determine whether a variable is empty i.e. it doesn’t exist or value equals FALSE.
isset($var) -- Determine if a variable is declared and value is different than NULL
unset($var) -- Unset a given variable or, destroys a variable
print_r ($var) -- Prints human-readable information about a variable
var_dump($var) -- Dumps information about a variable
Array Functions count($a) -- Count all elements in an array
array_key_exists('first', $search_array) -- Checks if the given key or index exists in the array
array_keys($array) -- Return all the keys of an array
array_values($array) -- Return all the values of an array
array_push($stack, "apple", "raspberry") -- Push one or more elements onto the end of array
array_pop($stack) -- Pop the element off the end of array
array_unshift($queue, "apple", "raspberry") -- Prepend one or more elements to the beginning
of an array
array_shift($stack) -- Shift an element off the beginning of array
array_search('green', $array) -- Searches the array for a given value and returns the first
corresponding key if successful
array_slice($input, 0, 3) -- Extract a slice of the array
array_splice($input, -1, 1, array("black", "maroon")) -- Remove a portion of the array and
replace it with something else
sort($array), rsort($array), ksort($array), krsort($array)
String Functions strlen(‘abcd’) -- Get string length
echo "Hello World" -- Output one or more strings
explode(" ", $pizza) -- split a string by a string
implode(",", $array) -- Join array elements with a string
htmlentities("A 'quote' is <b>bold</b>") -- Convert all applicable characters to HTML entities
html_entity_decode(“I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt”) -- Convert HTML
entities to their corresponding characters
htmlspecialchars($str) — Convert special characters to HTML entities
htmlspecialchars_decode($encodedstr) — Convert special HTML entities back to characters
md5($password) – calculate the md5 hashing of user string
sha1($password) – calculate the sha1 hashing of user string
parse_str($str,$output_array) -- Parses the string into variables
example:
$str = "first=value&arr[]=foo+bar&arr[]=baz";
// Recommended
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

More Related Content

What's hot

Angular Notes.pdf
Angular Notes.pdfAngular Notes.pdf
Angular Notes.pdfsagarpal60
 
Amazon kinesis와 elasticsearch service로 만드는 실시간 데이터 분석 플랫폼 :: 박철수 :: AWS Summi...
Amazon kinesis와 elasticsearch service로 만드는 실시간 데이터 분석 플랫폼 :: 박철수 :: AWS Summi...Amazon kinesis와 elasticsearch service로 만드는 실시간 데이터 분석 플랫폼 :: 박철수 :: AWS Summi...
Amazon kinesis와 elasticsearch service로 만드는 실시간 데이터 분석 플랫폼 :: 박철수 :: AWS Summi...Amazon Web Services Korea
 
Elastic Kubernetes Services (EKS)
Elastic Kubernetes Services (EKS)Elastic Kubernetes Services (EKS)
Elastic Kubernetes Services (EKS)sriram_rajan
 
개발자가 알아야 할 Amazon DynamoDB 활용법 :: 김일호 :: AWS Summit Seoul 2016
개발자가 알아야 할 Amazon DynamoDB 활용법 :: 김일호 :: AWS Summit Seoul 2016개발자가 알아야 할 Amazon DynamoDB 활용법 :: 김일호 :: AWS Summit Seoul 2016
개발자가 알아야 할 Amazon DynamoDB 활용법 :: 김일호 :: AWS Summit Seoul 2016Amazon Web Services Korea
 
EKS를 통한 차량 공유 서비스 '타다' 서비스 구축기 - 김태호, VCNC :: AWS Summit Seoul 2019
EKS를 통한 차량 공유 서비스 '타다' 서비스 구축기 - 김태호, VCNC :: AWS Summit Seoul 2019EKS를 통한 차량 공유 서비스 '타다' 서비스 구축기 - 김태호, VCNC :: AWS Summit Seoul 2019
EKS를 통한 차량 공유 서비스 '타다' 서비스 구축기 - 김태호, VCNC :: AWS Summit Seoul 2019Amazon Web Services Korea
 
성공적인 AWS클라우드로의 여정 그리고 5가지 궁금한 점 :: 김재성 :: AWS Summit Seoul 2016
성공적인 AWS클라우드로의 여정 그리고 5가지 궁금한 점 :: 김재성 :: AWS Summit Seoul 2016성공적인 AWS클라우드로의 여정 그리고 5가지 궁금한 점 :: 김재성 :: AWS Summit Seoul 2016
성공적인 AWS클라우드로의 여정 그리고 5가지 궁금한 점 :: 김재성 :: AWS Summit Seoul 2016Amazon Web Services Korea
 
An introduction to AWS CloudFormation - Pop-up Loft Tel Aviv
An introduction to AWS CloudFormation - Pop-up Loft Tel AvivAn introduction to AWS CloudFormation - Pop-up Loft Tel Aviv
An introduction to AWS CloudFormation - Pop-up Loft Tel AvivAmazon Web Services
 
Steps to Create odbc connection linux
Steps to Create odbc connection linuxSteps to Create odbc connection linux
Steps to Create odbc connection linuxOsama Mustafa
 
Masterclass Webinar - AWS CloudFormation
Masterclass Webinar - AWS CloudFormationMasterclass Webinar - AWS CloudFormation
Masterclass Webinar - AWS CloudFormationAmazon Web Services
 
SQL to NoSQL Best Practices with Amazon DynamoDB - AWS July 2016 Webinar Se...
SQL to NoSQL   Best Practices with Amazon DynamoDB - AWS July 2016 Webinar Se...SQL to NoSQL   Best Practices with Amazon DynamoDB - AWS July 2016 Webinar Se...
SQL to NoSQL Best Practices with Amazon DynamoDB - AWS July 2016 Webinar Se...Amazon Web Services
 
Container orchestration overview
Container orchestration overviewContainer orchestration overview
Container orchestration overviewWyn B. Van Devanter
 
AWS와 함께하는 클라우드 컴퓨팅 - 강철, AWS 어카운트 매니저 :: AWS Builders 100
AWS와 함께하는 클라우드 컴퓨팅 - 강철, AWS 어카운트 매니저 :: AWS Builders 100AWS와 함께하는 클라우드 컴퓨팅 - 강철, AWS 어카운트 매니저 :: AWS Builders 100
AWS와 함께하는 클라우드 컴퓨팅 - 강철, AWS 어카운트 매니저 :: AWS Builders 100Amazon Web Services Korea
 
Introducing AWS Elastic Beanstalk
Introducing AWS Elastic BeanstalkIntroducing AWS Elastic Beanstalk
Introducing AWS Elastic BeanstalkAmazon Web Services
 
AWS를 이용한 렌더링 아키텍처 및 사용 사례 :: 박철수 솔루션즈 아키텍트 :: AWS Media Day
AWS를 이용한 렌더링 아키텍처 및 사용 사례 :: 박철수 솔루션즈 아키텍트 :: AWS Media DayAWS를 이용한 렌더링 아키텍처 및 사용 사례 :: 박철수 솔루션즈 아키텍트 :: AWS Media Day
AWS를 이용한 렌더링 아키텍처 및 사용 사례 :: 박철수 솔루션즈 아키텍트 :: AWS Media DayAmazon Web Services Korea
 
Automated Schema Design for NoSQL Databases
Automated Schema Design for NoSQL DatabasesAutomated Schema Design for NoSQL Databases
Automated Schema Design for NoSQL DatabasesMichael Mior
 
금융 X 하이브리드 클라우드 플랫폼 - 한화생명 디지털 트랜스포메이션 전략 - 김나영 AWS 금융부문 사업개발 담당 / 박인규 AWS 금융...
금융 X 하이브리드 클라우드 플랫폼 - 한화생명 디지털 트랜스포메이션 전략 - 김나영 AWS 금융부문 사업개발 담당 / 박인규 AWS 금융...금융 X 하이브리드 클라우드 플랫폼 - 한화생명 디지털 트랜스포메이션 전략 - 김나영 AWS 금융부문 사업개발 담당 / 박인규 AWS 금융...
금융 X 하이브리드 클라우드 플랫폼 - 한화생명 디지털 트랜스포메이션 전략 - 김나영 AWS 금융부문 사업개발 담당 / 박인규 AWS 금융...Amazon Web Services Korea
 
Google Cloud IAM 계정, 권한 및 조직 관리
Google Cloud IAM 계정, 권한 및 조직 관리Google Cloud IAM 계정, 권한 및 조직 관리
Google Cloud IAM 계정, 권한 및 조직 관리정명훈 Jerry Jeong
 
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016Amazon Web Services Korea
 
java memory management & gc
java memory management & gcjava memory management & gc
java memory management & gcexsuns
 

What's hot (20)

Angular Notes.pdf
Angular Notes.pdfAngular Notes.pdf
Angular Notes.pdf
 
Amazon kinesis와 elasticsearch service로 만드는 실시간 데이터 분석 플랫폼 :: 박철수 :: AWS Summi...
Amazon kinesis와 elasticsearch service로 만드는 실시간 데이터 분석 플랫폼 :: 박철수 :: AWS Summi...Amazon kinesis와 elasticsearch service로 만드는 실시간 데이터 분석 플랫폼 :: 박철수 :: AWS Summi...
Amazon kinesis와 elasticsearch service로 만드는 실시간 데이터 분석 플랫폼 :: 박철수 :: AWS Summi...
 
Elastic Kubernetes Services (EKS)
Elastic Kubernetes Services (EKS)Elastic Kubernetes Services (EKS)
Elastic Kubernetes Services (EKS)
 
개발자가 알아야 할 Amazon DynamoDB 활용법 :: 김일호 :: AWS Summit Seoul 2016
개발자가 알아야 할 Amazon DynamoDB 활용법 :: 김일호 :: AWS Summit Seoul 2016개발자가 알아야 할 Amazon DynamoDB 활용법 :: 김일호 :: AWS Summit Seoul 2016
개발자가 알아야 할 Amazon DynamoDB 활용법 :: 김일호 :: AWS Summit Seoul 2016
 
EKS를 통한 차량 공유 서비스 '타다' 서비스 구축기 - 김태호, VCNC :: AWS Summit Seoul 2019
EKS를 통한 차량 공유 서비스 '타다' 서비스 구축기 - 김태호, VCNC :: AWS Summit Seoul 2019EKS를 통한 차량 공유 서비스 '타다' 서비스 구축기 - 김태호, VCNC :: AWS Summit Seoul 2019
EKS를 통한 차량 공유 서비스 '타다' 서비스 구축기 - 김태호, VCNC :: AWS Summit Seoul 2019
 
성공적인 AWS클라우드로의 여정 그리고 5가지 궁금한 점 :: 김재성 :: AWS Summit Seoul 2016
성공적인 AWS클라우드로의 여정 그리고 5가지 궁금한 점 :: 김재성 :: AWS Summit Seoul 2016성공적인 AWS클라우드로의 여정 그리고 5가지 궁금한 점 :: 김재성 :: AWS Summit Seoul 2016
성공적인 AWS클라우드로의 여정 그리고 5가지 궁금한 점 :: 김재성 :: AWS Summit Seoul 2016
 
An introduction to AWS CloudFormation - Pop-up Loft Tel Aviv
An introduction to AWS CloudFormation - Pop-up Loft Tel AvivAn introduction to AWS CloudFormation - Pop-up Loft Tel Aviv
An introduction to AWS CloudFormation - Pop-up Loft Tel Aviv
 
Steps to Create odbc connection linux
Steps to Create odbc connection linuxSteps to Create odbc connection linux
Steps to Create odbc connection linux
 
Masterclass Webinar - AWS CloudFormation
Masterclass Webinar - AWS CloudFormationMasterclass Webinar - AWS CloudFormation
Masterclass Webinar - AWS CloudFormation
 
SQL to NoSQL Best Practices with Amazon DynamoDB - AWS July 2016 Webinar Se...
SQL to NoSQL   Best Practices with Amazon DynamoDB - AWS July 2016 Webinar Se...SQL to NoSQL   Best Practices with Amazon DynamoDB - AWS July 2016 Webinar Se...
SQL to NoSQL Best Practices with Amazon DynamoDB - AWS July 2016 Webinar Se...
 
Container orchestration overview
Container orchestration overviewContainer orchestration overview
Container orchestration overview
 
AWS와 함께하는 클라우드 컴퓨팅 - 강철, AWS 어카운트 매니저 :: AWS Builders 100
AWS와 함께하는 클라우드 컴퓨팅 - 강철, AWS 어카운트 매니저 :: AWS Builders 100AWS와 함께하는 클라우드 컴퓨팅 - 강철, AWS 어카운트 매니저 :: AWS Builders 100
AWS와 함께하는 클라우드 컴퓨팅 - 강철, AWS 어카운트 매니저 :: AWS Builders 100
 
Introducing AWS Elastic Beanstalk
Introducing AWS Elastic BeanstalkIntroducing AWS Elastic Beanstalk
Introducing AWS Elastic Beanstalk
 
AWS를 이용한 렌더링 아키텍처 및 사용 사례 :: 박철수 솔루션즈 아키텍트 :: AWS Media Day
AWS를 이용한 렌더링 아키텍처 및 사용 사례 :: 박철수 솔루션즈 아키텍트 :: AWS Media DayAWS를 이용한 렌더링 아키텍처 및 사용 사례 :: 박철수 솔루션즈 아키텍트 :: AWS Media Day
AWS를 이용한 렌더링 아키텍처 및 사용 사례 :: 박철수 솔루션즈 아키텍트 :: AWS Media Day
 
React js for beginners
React js for beginnersReact js for beginners
React js for beginners
 
Automated Schema Design for NoSQL Databases
Automated Schema Design for NoSQL DatabasesAutomated Schema Design for NoSQL Databases
Automated Schema Design for NoSQL Databases
 
금융 X 하이브리드 클라우드 플랫폼 - 한화생명 디지털 트랜스포메이션 전략 - 김나영 AWS 금융부문 사업개발 담당 / 박인규 AWS 금융...
금융 X 하이브리드 클라우드 플랫폼 - 한화생명 디지털 트랜스포메이션 전략 - 김나영 AWS 금융부문 사업개발 담당 / 박인규 AWS 금융...금융 X 하이브리드 클라우드 플랫폼 - 한화생명 디지털 트랜스포메이션 전략 - 김나영 AWS 금융부문 사업개발 담당 / 박인규 AWS 금융...
금융 X 하이브리드 클라우드 플랫폼 - 한화생명 디지털 트랜스포메이션 전략 - 김나영 AWS 금융부문 사업개발 담당 / 박인규 AWS 금융...
 
Google Cloud IAM 계정, 권한 및 조직 관리
Google Cloud IAM 계정, 권한 및 조직 관리Google Cloud IAM 계정, 권한 및 조직 관리
Google Cloud IAM 계정, 권한 및 조직 관리
 
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016
게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016
 
java memory management & gc
java memory management & gcjava memory management & gc
java memory management & gc
 

Similar to Web 8 | Introduction to PHP

Similar to Web 8 | Introduction to PHP (20)

Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
 
2014 database - course 2 - php
2014 database - course 2 - php2014 database - course 2 - php
2014 database - course 2 - php
 
Php Lecture Notes
Php Lecture NotesPhp Lecture Notes
Php Lecture Notes
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!
 
slidesharenew1
slidesharenew1slidesharenew1
slidesharenew1
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
Introduction in php part 2
Introduction in php part 2Introduction in php part 2
Introduction in php part 2
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?
 
Intro to PHP
Intro to PHPIntro to PHP
Intro to PHP
 
07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards
 
My shell
My shellMy shell
My shell
 
Mike King - Storytelling by Numbers MKTFEST 2014
Mike King - Storytelling by Numbers MKTFEST 2014Mike King - Storytelling by Numbers MKTFEST 2014
Mike King - Storytelling by Numbers MKTFEST 2014
 
Storytelling By Numbers
Storytelling By NumbersStorytelling By Numbers
Storytelling By Numbers
 

More from Mohammad Imam Hossain

DS & Algo 4 - Graph and Shortest Path Search
DS & Algo 4 - Graph and Shortest Path SearchDS & Algo 4 - Graph and Shortest Path Search
DS & Algo 4 - Graph and Shortest Path SearchMohammad Imam Hossain
 
DS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL IntroductionDS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL IntroductionMohammad Imam Hossain
 
DBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational SchemaDBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational SchemaMohammad Imam Hossain
 
DBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaDBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaMohammad Imam Hossain
 
TOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity CheckTOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity CheckMohammad Imam Hossain
 

More from Mohammad Imam Hossain (20)

DS & Algo 6 - Offline Assignment 6
DS & Algo 6 - Offline Assignment 6DS & Algo 6 - Offline Assignment 6
DS & Algo 6 - Offline Assignment 6
 
DS & Algo 6 - Dynamic Programming
DS & Algo 6 - Dynamic ProgrammingDS & Algo 6 - Dynamic Programming
DS & Algo 6 - Dynamic Programming
 
DS & Algo 5 - Disjoint Set and MST
DS & Algo 5 - Disjoint Set and MSTDS & Algo 5 - Disjoint Set and MST
DS & Algo 5 - Disjoint Set and MST
 
DS & Algo 4 - Graph and Shortest Path Search
DS & Algo 4 - Graph and Shortest Path SearchDS & Algo 4 - Graph and Shortest Path Search
DS & Algo 4 - Graph and Shortest Path Search
 
DS & Algo 3 - Offline Assignment 3
DS & Algo 3 - Offline Assignment 3DS & Algo 3 - Offline Assignment 3
DS & Algo 3 - Offline Assignment 3
 
DS & Algo 3 - Divide and Conquer
DS & Algo 3 - Divide and ConquerDS & Algo 3 - Divide and Conquer
DS & Algo 3 - Divide and Conquer
 
DS & Algo 2 - Offline Assignment 2
DS & Algo 2 - Offline Assignment 2DS & Algo 2 - Offline Assignment 2
DS & Algo 2 - Offline Assignment 2
 
DS & Algo 2 - Recursion
DS & Algo 2 - RecursionDS & Algo 2 - Recursion
DS & Algo 2 - Recursion
 
DS & Algo 1 - Offline Assignment 1
DS & Algo 1 - Offline Assignment 1DS & Algo 1 - Offline Assignment 1
DS & Algo 1 - Offline Assignment 1
 
DS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL IntroductionDS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL Introduction
 
DBMS 1 | Introduction to DBMS
DBMS 1 | Introduction to DBMSDBMS 1 | Introduction to DBMS
DBMS 1 | Introduction to DBMS
 
DBMS 10 | Database Transactions
DBMS 10 | Database TransactionsDBMS 10 | Database Transactions
DBMS 10 | Database Transactions
 
DBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational SchemaDBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational Schema
 
DBMS 2 | Entity Relationship Model
DBMS 2 | Entity Relationship ModelDBMS 2 | Entity Relationship Model
DBMS 2 | Entity Relationship Model
 
DBMS 7 | Relational Query Language
DBMS 7 | Relational Query LanguageDBMS 7 | Relational Query Language
DBMS 7 | Relational Query Language
 
DBMS 4 | MySQL - DDL & DML Commands
DBMS 4 | MySQL - DDL & DML CommandsDBMS 4 | MySQL - DDL & DML Commands
DBMS 4 | MySQL - DDL & DML Commands
 
DBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaDBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR Schema
 
TOC 10 | Turing Machine
TOC 10 | Turing MachineTOC 10 | Turing Machine
TOC 10 | Turing Machine
 
TOC 9 | Pushdown Automata
TOC 9 | Pushdown AutomataTOC 9 | Pushdown Automata
TOC 9 | Pushdown Automata
 
TOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity CheckTOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity Check
 

Recently uploaded

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 

Recently uploaded (20)

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 

Web 8 | Introduction to PHP

  • 1. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com Introduction to PHP (Hypertext Preprocessor) PHP Tags: When PHP parses a file, it looks for opening and closing tags, which are <?php and ?> which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser. <p>This is going to be ignored by PHP and displayed by the browser.</p> <?php echo 'While this is going to be parsed.'; ?> <p>This will also be ignored by PHP and displayed by the browser.</p> For outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the text through echo or print. <?php if ($expression == true){ ?> This will show if the expression is true. <?php } else { ?> Otherwise this will show. <?php } ?> PHP Comments: <?php echo 'This is a test'; // This is a one-line c++ style comment /* This is a multi line comment yet another line of comment */ echo 'This is yet another test'; echo 'One Final Test'; # This is a one-line shell-style comment ?> PHP Datatypes: Boolean (TRUE/FALSE) – case insensitive False – FALSE, 0, -0, 0.0, -0.0, “”, “0”, array with zero elements, NULL (including unset variables) True – Every other value including NAN Integer <?php $a = 1234; // decimal number $a = -123; // a negative number $a = 0123; // octal number (equivalent to 83 decimal) $a = 0x1A; // hexadecimal number (equivalent to 26 decimal) $a = 0b11111111; // binary number (equivalent to 255 decimal) ?> 0 = False, Null 1 = True
  • 2. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com Floating Point Numbers <?php $a = 1.234; $b = 1.2e3; $c = 7E-10; ?> Strings (Single quoted/ Double quoted) <?php echo 'this is a simple string'; // Outputs: Arnold once said: "I'll be back" echo 'Arnold once said: "I'll be back"'; // Outputs: You deleted C:*.*? echo 'You deleted C:*.*?'; // Outputs: This will not expand: n a newline echo 'This will not expand: n a newline'; // Outputs: Variables do not $expand $either echo 'Variables do not $expand $either'; ?> <?php $juice = "apple"; echo "He drank some $juice juice."; ?> <?php $str = 'abc'; var_dump($str[1]); var_dump(isset($str[1])); ?> . (DOT) – to concat strings “1” – True “” – False/ Null Array <?php $array = array( "foo" => "bar", "bar" => "foo", ); $array1 = array("foo", "bar", "hello", "world"); var_dump($array1); ?>
  • 3. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com <?php $array = array( "foo" => "bar", 42 => 24, "multi" => array( "dimensional" => array( "array" => "foo" ) ) ); var_dump($array["foo"]); var_dump($array[42]); var_dump($array["multi"]["dimensional"]["array"]); ?> <?php $arr = array(5 => 1, 12 => 2); $arr[13] = 56; // This is the same as $arr[13] = 56; // at this point of the script $arr["x"] = 42; // This adds a new element to // the array with key "x" unset($arr[5]); // This removes the element from the array unset($arr); // This deletes the whole array ?> PHP Variables: Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case- sensitive. <?php $a = 1; /* global scope */ function test() { echo $a; /* reference to local scope variable */ } test(); ?> <?php $a = 1; $b = 2; function Sum() { $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b']; } Sum(); echo $b; ?>
  • 4. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com Predefined Variables: $GLOBALS – References all variables available in global scope <?php function test() { $foo = "local variable"; echo '$foo in global scope: ' . $GLOBALS["foo"] . "n"; echo '$foo in current scope: ' . $foo . "n"; } $foo = "Example content"; test(); ?> $_SERVER – server and execution environment information <?php $indicesServer = array( 'PHP_SELF', 'SERVER_ADDR', 'SERVER_NAME', 'SERVER_PROTOCOL', 'REQUEST_METHOD', 'REQUEST_TIME', 'QUERY_STRING', 'DOCUMENT_ROOT', 'HTTPS', 'REMOTE_ADDR', 'REMOTE_HOST', 'REMOTE_PORT', 'REMOTE_USER', 'SERVER_PORT', 'SCRIPT_NAME', 'REQUEST_URI') ; echo '<table style=”width:100%;”>' ; foreach ($indicesServer as $arg) { if (isset($_SERVER[$arg])) { echo '<tr><td>'.$arg.'</td><td>' . $_SERVER[$arg] . '</td></tr>' ; } else { echo '<tr><td>'.$arg.'</td><td>-</td></tr>' ; } } echo '</table>' ; ?> $_GET – an associative array of variables passed to the current script via the URL parameters $_POST – an associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or, multipart/form-data as the HTTP $_FILES – an associative array of items uploaded to the current script via the HTTP POST method $_REQUEST -- An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE. $_SESSION -- An associative array containing session variables available to the current script. $_COOKIE -- An associative array of variables passed to the current script via HTTP Cookies.
  • 5. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com Operators and Operator Precedence: visit here  https://www.php.net/manual/en/language.operators.php Control Structures: if-elseif-else statement <?php if ($a > $b) { echo "a is bigger than b"; } elseif ($a == $b) { echo "a is equal to b"; } else { echo "a is smaller than b"; } ?> while loop <?php $i = 1; while ($i <= 10) { echo $i++; /* the printed value would be $i before the increment (post-increment) */ } ?> do-while loop <?php $i = 0; do { echo $i; } while ($i > 0); ?> for loop <?php for ($i = 1; $i <= 10; $i++) { echo $i; } ?> foreach loop <?php $a = array(1, 2, 3, 17); $i = 0; foreach ($a as $v) { echo "$a[$i] => $v.n"; $i++; } $a = array( "one" => 1, "two" => 2,
  • 6. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com "three" => 3, "seventeen" => 17 ); foreach ($a as $k => $v) { echo "$a[$k] => $v.n"; } //multi-dimensional array $a = array(); $a[0][0] = "a"; $a[0][1] = "b"; $a[1][0] = "y"; $a[1][1] = "z"; foreach ($a as $v1) { foreach ($v1 as $v2) { echo "$v2n"; } } ?> break, continue, switch, return similar as before include/require The include/require statement includes and evaluates the specified file. The include construct will emit a warning if it cannot find a file; this is different behavior from require, which will emit a fatal error. within vars.php file <?php $color = 'green'; $fruit = 'apple'; ?> within test.php file <?php echo "A $color $fruit"; // A include 'vars.php'; echo "A $color $fruit"; // A green apple ?> include_once / require_once The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again, and include_once returns TRUE. As the name suggests, the file will be included just once. <?php var_dump(include_once 'fakefile.ext'); // bool(false) var_dump(include_once 'fakefile.ext'); // bool(true) ?>
  • 7. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com Functions: <?php $makefoo = true; /* We can't call foo() from here since it doesn't exist yet, but we can call bar() */ bar(); if ($makefoo) { function foo() { echo "I don't exist until program execution reaches me.n"; } } /* Now we can safely call foo() since $makefoo evaluated to true */ if ($makefoo) foo(); function bar() { echo "I exist immediately upon program start.n"; } ?> <?php function foo() { function bar() { echo "I don't exist until foo() is called.n"; } } /* We can't call bar() yet since it doesn't exist. */ foo(); /* Now we can call bar(), foo()'s processing has made it accessible. */ bar(); ?> ///anonymous functions in PHP <?php $greet = function($name) { printf("Hello %srn", $name); }; $greet('World'); $greet('PHP'); ?>
  • 8. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com Some Functions: Variable Handling Functions empty($var) -- Determine whether a variable is empty i.e. it doesn’t exist or value equals FALSE. isset($var) -- Determine if a variable is declared and value is different than NULL unset($var) -- Unset a given variable or, destroys a variable print_r ($var) -- Prints human-readable information about a variable var_dump($var) -- Dumps information about a variable Array Functions count($a) -- Count all elements in an array array_key_exists('first', $search_array) -- Checks if the given key or index exists in the array array_keys($array) -- Return all the keys of an array array_values($array) -- Return all the values of an array array_push($stack, "apple", "raspberry") -- Push one or more elements onto the end of array array_pop($stack) -- Pop the element off the end of array array_unshift($queue, "apple", "raspberry") -- Prepend one or more elements to the beginning of an array array_shift($stack) -- Shift an element off the beginning of array array_search('green', $array) -- Searches the array for a given value and returns the first corresponding key if successful array_slice($input, 0, 3) -- Extract a slice of the array array_splice($input, -1, 1, array("black", "maroon")) -- Remove a portion of the array and replace it with something else sort($array), rsort($array), ksort($array), krsort($array) String Functions strlen(‘abcd’) -- Get string length echo "Hello World" -- Output one or more strings explode(" ", $pizza) -- split a string by a string implode(",", $array) -- Join array elements with a string htmlentities("A 'quote' is <b>bold</b>") -- Convert all applicable characters to HTML entities html_entity_decode(“I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt”) -- Convert HTML entities to their corresponding characters htmlspecialchars($str) — Convert special characters to HTML entities htmlspecialchars_decode($encodedstr) — Convert special HTML entities back to characters md5($password) – calculate the md5 hashing of user string sha1($password) – calculate the sha1 hashing of user string parse_str($str,$output_array) -- Parses the string into variables example: $str = "first=value&arr[]=foo+bar&arr[]=baz"; // Recommended parse_str($str, $output); echo $output['first']; // value echo $output['arr'][0]; // foo bar echo $output['arr'][1]; // baz