PHP Face question Summary One (basic article with answer)

Source: Internet
Author: User
Tags array sort configuration php explode php class print format

A good PHP interview questions, with the answer, there are ready to change the work of the students can refer to.

1: Use more than five ways to get a file's extension
Requirements: dir/upload.image.jpg, find. jpg or JPG,
Must be handled using PHP's own processing function, which cannot be significantly duplicated and can be encapsulated into functions such as GET_EXT1 ($file _name), get_ext2 ($file _name)


function Get_ext1 ($file _name) {    return strrchr ($file _name, '. ');} function get_ext2 ($file _name) {    return substr ($file _name, Strrpos ($file _name, '. '));} function Get_ext3 ($file _name) {    return Array_pop (Explode ('. ', $file _name));} function Get_ext4 ($file _name) {    return pathinfo ($file _name, pathinfo_extension);} function Get_ext5 ($file _name) {    return Strrev (substr (Strrev ($file _name), 0, Strpos (strrev ($file _name), '. ')));}

2. Using PHP to describe the bubble sort and quick sort algorithm, an object can be an array

Parse: Bubble sort (Array sort)

function Bubble_sort ($array) {    $count = count ($array);    if ($count <= 0) return false;    for ($i =0; $i < $count; $i + +) {for        ($j = $i; $j < $count-1; $j + +) {            if ($array [$i] > $array [$j]) {                $tmp = $ array[$i];                $array [$i] = $array [$j];                $array [$j] = $tmp;            }        }    }    return $array;}

Quick sort (Array sort)

function Quick_sort ($array) {    if (count ($array) <= 1) return $array;    $key = $array [0];    $left _arr = Array ();    $right _arr = Array ();    for ($i =1; $i <count ($array), $i + +) {        if ($array [$i] <= $key)            $left _arr[] = $array [$i];        else            $right _arr[] = $array [$i];    }    $left _arr = Quick_sort ($left _arr);    $right _arr = Quick_sort ($right _arr);    Return Array_merge ($left _arr, Array ($key), $right _arr);}

3. Using PHP to describe order lookup and binary lookup (also called binary lookup) algorithm, sequential lookup must consider efficiency, an object can be an ordered array

Parse://Two-point lookup (Find an element in an array)

function Bin_sch ($array, $low, $high, $k) {    if ($low <= $high) {    $mid = intval (($low + $high)/2);    if ($array [$mid] = = $k) {    return $mid;    } ElseIf ($k < $array [$mid]) {    return Bin_sch ($array, $low, $mid-1, $k);    } else{    return Bin_sch ($array, $mid +1, $high, $k);    }    }    return-1;}

Order lookup (Find an element in an array)

function Seq_sch ($array, $n, $k) {    $array [$n] = $k;    for ($i =0; $i < $n; $i + +) {        if ($array [$i]== $k) {break            ;        }    }    if ($i < $n) {        return $i;    } else{        return-1;    }}

4. Write a two-dimensional array sorting algorithm function, which can be universal, call PHP built-in functions

Parsing://two-dimensional array sorting, $arr is the data, $keys is the ranking of the health value, $order is the collation, 1 is ascending, 0 is descending

function Array_sort ($arr, $keys, $order =0) {    if (!is_array ($arr)) {        return false;    }    $keysvalue = Array ();    foreach ($arr as $key = + $val) {        $keysvalue [$key] = $val [$keys];    }    if ($order = = 0) {        asort ($keysvalue);    } else {        arsort ($keysvalue);    }    Reset ($keysvalue);    foreach ($keysvalue as $key = + $vals) {        $keysort [$key] = $key;    }    $new _array = Array ();    foreach ($keysort as $key = + $val) {        $new _array[$key] = $arr [$val];    }    return $new _array;}

5: Crawl remote pictures to local, what function would you use?
Resolution: Fsockopen
6:javascript can define a two-dimensional array, and if not, how can you solve it?

Parsing: JavaScript does not support two-dimensional array definitions and can be resolved with arr[0] = new Array ()

7: Browsing the current page user's IP address


echo $_server["REMOTE_ADDR"]//query string (the first question mark in the URL?) ): Id=1&bi=2echo $_server["Query_string"]//the document root directory where the current script is running: D:inetpubwwwrootecho $_server["Document_root"

8, in HTTP 1.0, the meaning of status Code 401 is not authorized ____; If you return a prompt for "file not found", the header function is available, and its statement is?
Resolution: 401 means Unauthorized; header ("http/1.0 404 Not Found");

Print the previous day in PHP, the print format is May 10, 2007 22:21:21

9: Use regular Expressions (Regular expression) to write a function to verify that the e-mail message is in the correct format.


<?php$email=$_post[' email '];if (!preg_match ('/^[\w. [Email protected] ([\w.] +)\. [A-z] {2,6}$/i ', $email))  {echo "e-mail detection failed";} Else{echo "e-mail detection Success";}? >

10: Write code showing client IP and server IP in PHP


Print client Ip:echo $_server[' REMOTE_ADDR '); or: getenv (' remote_addr '); print server Ip:echo gethostbyname (' ')

11: How to modify the lifetime of the session (do not modify the configuration php.ini session.gc_maxlifetime parameters)?

Resolution: Session_set_cookie_params ($lifeTime);

12: There is a web address, such as the PHP Development Resource Network Home page:, how to get its content?

Parsing: Method 1 (for PHP5 and later versions):

< $readcontents = fopen ("", "RB"); $contents = Stream_get_contents ($readcontents) ; fclose ($readcontents); Echo $contents;? >

Method 2:

<?echo file_get_contents (' ');? >

13, please explain the difference between the value and the reference in PHP. When is the value passed? (2 points)


Pass by value: Any change to a value within a function is ignored outside of the function by reference: Any change in value within a function can also reflect the pros and cons of these modifications outside the function: when passed by value, PHP must copy the value. This can be a costly operation, especially for large strings and objects. Passing by reference does not require copying values, which is good for performance gains.

14: Write a function, as efficiently as possible, to remove the file extension from a standard URL, for example: need to remove PHP or. php
Answer 1:

function Getext ($url) {$arr = Parse_url ($url);  $file = basename ($arr [' path ']);  $ext = Explode ('. ', $file); return $ext [1];}

Answer 2:

function Getext ($url) {$url = basename ($url);  $pos 1 = strpos ($url, ".");  $pos 2 = Strpos ($url, "?"); if (Strstr ($url, "?"))

{return substr ($url, $pos 1); } }

What are the main differences between the field types in the 15:mysql database, varchar and char? What is the most efficient way to find a field?


VARCHAR is a variable length, saving storage space, char is fixed. Find efficiency to char type fast, because varchar is not fixed length, you must first find the length, then the data extraction, more than the char fixed-length type one more step, so less efficient

16: Write out the names of more than three MySQL database storage engines (hint: case insensitive)

MyISAM, InnoDB, BDB (Berkeley DB), Merge, Memory (Heap), Example, Federated, Archive, CSV, blackhole, MaxDB, etc. more than 10 engines

17: Please write a function that implements the following functions:
The string ' Open_door ' is converted to ' Opendoor ', ' make_by_id ' converted to ' Makebyid '.


Method One: Function Str_explode ($str) {    $str _arr=explode (' _ ', $str);    $str _implode=implode (', $str _arr);     $str _implode=implode (", Explode (", ucwords ($str _implode)));    return $str _implode;} $strexplode =str_explode (' make_by_id ');p rint_r ($strexplode); method Two: $str = ' make_by_id! '; $expStr =explode (' _ ', $str), for ($i =0; $i <count ($EXPSTR); $i + +) {    echo ucwords ($expStr [$i]);} Method Three: Echo str_replace (', ', ', Ucwords (Str_replace (' _ ', ' ', ' Open_door '))

18: The ID in a table has multiple records, the record of all this ID is detected, and shows the number of records in total, with SQL statements and views,
Stored procedures are implemented separately.


DELIMITER//create procedure Proc_countnum (in columnId int,out rowsno int) beginselect COUNT (*) to Rowsno from member whe Re Member_id=columnid;endcall proc_countnum (1, @no); Select @no; Method: View: Create View V_countnum as Select Member_id,count (* As Countnum from member group Bymember_idselect Countnum from V_countnum where member_id=1

19:echo count (' abc '); Output what?


Answer: 1count-calculates the number of cells in an array or the number of attributes in an object int count (mixed$var [, int $mode]), if Var is not an array type or an object that implements the countable interface, returns 1 with an exception if VA R is NULL then the result is 0. For an object, if SPL is installed, you can invoke count () by implementing the countable interface. The interface has only one method count (), and this method returns the return value of the count () function.

What is the difference between static,public,private,protected in 20:php class?

Statically static, the class name can be accessed public to represent the global, the class inside the outer subclass can be accessed; private means that only this class can be used internally; protected is protected and accessible only in this class or subclass or parent class;

What is the difference between get, post, and head in the 21:http protocol?


HEAD: Only the header of the page is requested. GET: Requests the specified page information and returns the entity principal. POST: The requesting server accepts the specified document as a new subordinate entity for the identified URI. (1) HTTP defines different ways to interact with the server, with the most basic approach being GET and POST. In fact GET applies to most requests, while retaining POST is only used to update the site. (2) When the form is submitted, if you do not specify method, the default is a GET request, the data submitted in the form will be appended to the URL, separated from the URL. The alphanumeric character is sent as is, but the space is converted to the "+" sign, and the other symbol is converted to%XX, where XX is the ASCII (or ISO Latin-1) value that the symbol is represented in 16 binary. The GET request submits the data to be placed in the HTTP request protocol header, and the data submitted by the post is placed in the Entity data, and the data submitted by the Get method can only have 1024 bytes, while post does not have this limit. (3) GET This is the most common method that the browser uses to request the server. Post This method is also used to transfer data, but unlike get, when using post, the data is not appended to the URI, but rather as a separate line to pass, at this time must also send a CONTENT_LENGTH title to indicate the length of the data, followed by a blank line, Then the data is actually transferred. Web forms are usually sent by post.

22: Statements include and require can include another file in the current file, the difference is ____; to avoid including the same file multiple times, you can use the statement ____ instead of them?

Parsing: the include () generates a warning when handling failure, and require () causes a fatal error; Require_once ()/include_once ()

23: Write a function that can traverse all the files and subfolders under a folder.

Parsing: The code that someone else has written is concise enough and gives a lot of power.

<?php  function My_scandir ($dir)  {      $files =array ();      if (Is_dir ($dir))      {          if ($handle =opendir ($dir))          {while              (($file =readdir ($handle))!==false)              {                  if ($file! = "." && $file! = "...")                  {                      if (Is_dir ($dir. ") /". $file)                      " {                          $files [$file]=my_scandir ($dir. ") /". $file);                      }                      else                      {                          $files []= $dir.] /". $file;}}              }              Closedir ($handle);              return $files;  }}} echo "<pre>";  Print_r (My_scandir ("D:\DouJia-3.5"));  

PHP Face question summary One (basic article with answer)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.