All topics

PHP interview questions

17 questions with answers. 116 open jobs in India ask for PHP.

  1. Why shouldn't I use mysql_* functions in PHP?

    The MySQL extension:

    • Is not under active development
    • Is officially deprecated as of PHP 5.5 (released June 2013).
    • Has been removed entirely as of PHP 7.0 (released December 2015)
      • This means that as of 31 Dec 2018 it does not exist in any supported version of PHP. If you are using a version of PHP which supports it, you are using a version which doesn't get security problems fixed.
    • Lacks an OO interface
    • Doesn't support:
      • Non-blocking, asynchronous queries
      • Prepared statements or parameterized queries
      • Stored procedures
      • Multiple Statements
      • Transactions
      • The "new" password authentication method (on by default in MySQL 5.6; required in 5.7)
      • Any of the new functionality in MySQL 5.1 or later

    Since it is deprecated, using it makes your code less future proof.

    Lack of support for prepared statements is particularly important as they provide a clearer, less error-prone method of escaping and quoting external data than manually escaping it with a separate function call.

    See the comparison of SQL extensions.

    From Stack Overflow: asked by Madara's Ghost, answered by Quentin (CC BY-SA 4.0)

  2. How does PHP 'foreach' actually work?

    foreach supports iteration over three different kinds of values:

    In the following, I will try to explain precisely how iteration works in different cases. By far the simplest case is Traversable objects, as for these foreach is essentially only syntax sugar for code along these lines:

    foreach ($it as $k => $v) { /* ... */ }
    /* translates to: */
    if ($it instanceof IteratorAggregate) {
        $it = $it->getIterator();
    }
    for ($it->rewind(); $it->valid(); $it->next()) {
        $v = $it->current();
        $k = $it->key();
        /* ... */
    }
    

    For internal classes, actual method calls are avoided by using an internal API that essentially just mirrors the Iterator interface on the C level.

    Iteration of arrays and plain objects is significantly more complicated. First of all, it should be noted that in PHP "arrays" are really ordered dictionaries and they will be traversed according to this order (which matches the insertion order as long as you didn't use something like sort). This is opposed to iterating by the natural order of the keys (how lists in other languages often work) or having no defined order at all (how dictionaries in other languages often work).

    The same also applies to objects, as the object properties can be seen as another (ordered) dictionary mapping property names to their values, plus some visibility handling. In the majority of cases, the object properties are not actually stored in this rather inefficient way. However, if you start iterating over an object, the packed representation that is normally used will be converted to a real dictionary. At that point, iteration of plain objects becomes very similar to iteration of arrays (which is why I'm not discussing plain-object iteration much in here).

    So far, so good. Iterating over a dictionary can't be too hard, right? The problems begin when you realize that an array/object can change during iteration. There are multiple ways this can happen:

    • If you iterate by reference using foreach ($arr as &$v) then $arr is turned into a reference and you can change it during iteration.
    • In PHP 5 the same applies even if you iterate by value, but the array was a reference beforehand: $ref =& $arr; foreach ($ref as $v)
    • Objects have by-handle passing semantics, which for most practical purposes means that they behave like references. So objects can always be changed during iteration.

    The problem with allowing modifications during iteration is the case where the element you are currently on is removed. Say you use a pointer to keep track of which array element you are currently at. If this element is now freed, you are left with a dangling pointer (usually resulting in a segfault).

    There are different ways of solving this issue. PHP 5 and PHP 7 differ significantly in this regard and I'll describe both behaviors in the following. The summary is that PHP 5's approach was rather dumb and lead to all kinds of weird edge-case issues, while PHP 7's more involved approach results in more predictable and consistent behavior.

    As a last preliminary, it should be noted that PHP uses reference counting and copy-on-write to manage memory. This means that if you "copy" a value, you actually just reuse the old value and increment its reference count (refcount). Only once you perform some kind of modification a real copy (called a "duplication") will be done. See You're being lied to for a more extensive introduction on this topic.

    PHP 5

    Internal array pointer and HashPointer

    Arrays in PHP 5 have one dedicated "internal array pointer" (IAP), which properly supports modifications: Whenever an element is removed, there will be a check whether the IAP points to this element. If it does, it is advanced to the next element instead.

    Read the rest at the sourceFrom Stack Overflow: asked by DaveRandom, answered by NikiC (CC BY-SA 4.0)

  3. When should I use 'self' over '$this'?

    Short Answer

    Use $this to refer to the current object. Use self to refer to the current class. In other words, use $this->member for non-static members, use self::$member for static members.

    Full Answer

    Here is an example of correct usage of $this and self for non-static and static member variables:

    <?php
    class X {
        private $non_static_member = 1;
        private static $static_member = 2;
        function __construct() {
            echo $this->non_static_member . ' '
               . self::$static_member;
        }
    }
    new X();
    ?>
    

    Here is an example of incorrect usage of $this and self for non-static and static member variables:

    <?php
    class X {
        private $non_static_member = 1;
        private static $static_member = 2;
        function __construct() {
            echo self::$non_static_member . ' '
               . $this->static_member;
        }
    }
    new X();
    ?>
    

    Here is an example of polymorphism with $this for member functions:

    <?php
    class X {
        function foo() {
            echo 'X::foo()';
        }
        function bar() {
            $this->foo();
        }
    }
    class Y extends X {
        function foo() {
            echo 'Y::foo()';
        }
    }
    $x = new Y();
    $x->bar();
    ?>
    

    Here is an example of suppressing polymorphic behaviour by using self for member functions:

    <?php
    class X {
        function foo() {
            echo 'X::foo()';
        }
        function bar() {
            self::foo();
        }
    }
    class Y extends X {
        function foo() {
            echo 'Y::foo()';
        }
    }
    $x = new Y();
    $x->bar();
    ?>
    

    The idea is that $this->foo() calls the foo() member function of whatever is the exact type of the current object. If the object is of type X, it thus calls X::foo(). If the object is of type Y, it calls Y::foo(). But with self::foo(), X::foo() is always called.

    From http://www.phpbuilder.com/board/showthread.php?t=10354489:

    By http://board.phpbuilder.com/member.php?145249-laserlight

    From Stack Overflow: asked by Casey Watson, answered by John Millikin (CC BY-SA 4.0)

  4. Difference between require, include, require_once and include_once?

    There are require and include_once as well.

    So your question should be...

    1. When should I use require vs. include?
    2. When should I use require_once vs. require

    The answer to 1 is described here.

    The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.

    The answer to 2 can be found here.

    The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.

    Note that nowadays there is little use for *_once variants. If you are using them, it's likely either a mindless habit or your code needs to be restructured.

    From Stack Overflow: asked by Scott B, answered by Leo (CC BY-SA 4.0)

  5. What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

    In the examples below the client is the browser and the server is the webserver hosting the website.

    Before you can understand these technologies, you have to understand classic HTTP web traffic first.

    Regular HTTP:

    1. A client requests a webpage from a server.
    2. The server calculates the response
    3. The server sends the response to the client.

    Ajax Polling:

    1. A client requests a webpage from a server using regular HTTP (see HTTP above).
    2. The client receives the requested webpage and executes the JavaScript on the page which requests a file from the server at regular intervals (e.g. 0.5 seconds).
    3. The server calculates each response and sends it back, just like normal HTTP traffic.

    Ajax Long-Polling:

    1. A client requests a webpage from a server using regular HTTP (see HTTP above).
    2. The client receives the requested webpage and executes the JavaScript on the page which requests a file from the server.
    3. The server does not immediately respond with the requested information but waits until there's new information available.
    4. When there's new information available, the server responds with the new information.
    5. The client receives the new information and immediately sends another request to the server, re-starting the process.

    HTML5 Server Sent Events (SSE) / EventSource:

    1. A client requests a webpage from a server using regular HTTP (see HTTP above).
    2. The client receives the requested webpage and executes the JavaScript on the page which opens a connection to the server.
    3. The server sends an event to the client when there's new information available.

    HTML5 Websockets:

    1. A client requests a webpage from a server using regular http (see HTTP above).
    2. The client receives the requested webpage and executes the JavaScript on the page which opens a connection with the server.
    3. The server and the client can now send each other messages when new data (on either side) is available.

      • Real-time traffic from the server to the client and from the client to the server
      • You'll want to use a server that has an event loop
      • With WebSockets it is possible to connect with a server from another domain.
      • It is also possible to use a third party hosted websocket server, for example Pusher or others. This way you'll only have to implement the client side, which is very easy!
      • If you want to read more, I found these very useful: (article), (article) (tutorial).

    Comet:

    Read the rest at the sourceFrom Stack Overflow: asked by user1437328, answered by Tieme (CC BY-SA 4.0)

  6. What is stdClass in PHP?

    stdClass is PHP's generic empty class, kind of like Object in Java or object in Python (Edit: but not actually used as universal base class; thanks @Ciaran for pointing this out).

    It is useful for anonymous objects, dynamic properties, etc.

    An easy way to consider the StdClass is as an alternative to associative array. See this example below that shows how json_decode() allows to get an StdClass instance or an associative array. Also but not shown in this example, SoapClient::__soapCall returns an StdClass instance.

    <?php
    //Example with StdClass
    $json = '{ "foo": "bar", "number": 42 }';
    $stdInstance = json_decode($json);
    echo $stdInstance->foo . PHP_EOL; //"bar"
    echo $stdInstance->number . PHP_EOL; //42
    //Example with associative array
    $array = json_decode($json, true);
    echo $array['foo'] . PHP_EOL; //"bar"
    echo $array['number'] . PHP_EOL; //42
    

    See Dynamic Properties in PHP and StdClass for more examples.

    From Stack Overflow: asked by Keira Nighly, answered by Alex Martelli (CC BY-SA 3.0)

  7. What is the difference between public, private, and protected?

    You use:

    • public scope to make that property/method available from anywhere, other classes and instances of the object.

    • private scope when you want your property/method to be visible in its own class only.

    • protected scope when you want to make your property/method visible in all classes that extend current class including the parent class.

    If you don't use any visibility modifier, the property / method will be public.

    More: (For comprehensive information)

    From Stack Overflow: asked by Adam Halasz, answered by Sarfraz (CC BY-SA 4.0)

  8. Where can I find php.ini?

    On the command line execute:

    php --ini
    

    You will get something like:

    Configuration File (php.ini) Path: /etc/php5/cli
    Loaded Configuration File:         /etc/php5/cli/php.ini
    Scan for additional .ini files in: /etc/php5/cli/conf.d
    Additional .ini files parsed:      /etc/php5/cli/conf.d/curl.ini,
    /etc/php5/cli/conf.d/pdo.ini,
    /etc/php5/cli/conf.d/pdo_sqlite.ini,
    /etc/php5/cli/conf.d/sqlite.ini,
    /etc/php5/cli/conf.d/sqlite3.ini,
    /etc/php5/cli/conf.d/xdebug.ini,
    /etc/php5/cli/conf.d/xsl.ini
    

    That's from my local dev-machine. However, the second line is the interesting one. If there is nothing mentioned, have a look at the first one. That is the path, where PHP looks for the php.ini file.

    You can grep the same information using phpinfo() in a script and call it with a browser. It’s mentioned in the first block of the output. php -i does the same for the command line, but it’s quite uncomfortable.

    From Stack Overflow: asked by necromancer, answered by KingCrunch (CC BY-SA 4.0)

  9. What is thread safe or non-thread safe in PHP?

    Needed background on concurrency approaches:

    Different web servers implement different techniques for handling incoming HTTP requests in parallel. A pretty popular technique is using threads -- that is, the web server will create/dedicate a single thread for each incoming request. The Apache HTTP web server supports multiple models for handling requests, one of which (called the worker MPM) uses threads. But it supports another concurrency model called the prefork MPM which uses processes -- that is, the web server will create/dedicate a single process for each request.

    There are also other completely different concurrency models (using Asynchronous sockets and I/O), as well as ones that mix two or even three models together. For the purpose of answering this question, we are only concerned with the two models above, and taking Apache HTTP server as an example.

    Needed background on how PHP "integrates" with web servers:

    PHP itself does not respond to the actual HTTP requests -- this is the job of the web server. So we configure the web server to forward requests to PHP for processing, then receive the result and send it back to the user. There are multiple ways to chain the web server with PHP. For Apache HTTP Server, the most popular is "mod_php". This module is actually PHP itself, but compiled as a module for the web server, and so it gets loaded right inside it.

    There are other methods for chaining PHP with Apache and other web servers, but mod_php is the most popular one and will also serve for answering your question.

    You may not have needed to understand these details before, because hosting companies and GNU/Linux distros come with everything prepared for us.

    Now, onto your question!

    Since with mod_php, PHP gets loaded right into Apache, if Apache is going to handle concurrency using its Worker MPM (that is, using Threads) then PHP must be able to operate within this same multi-threaded environment -- meaning, PHP has to be thread-safe to be able to play ball correctly with Apache!

    At this point, you should be thinking "OK, so if I'm using a multi-threaded web server and I'm going to embed PHP right into it, then I must use the thread-safe version of PHP". And this would be correct thinking. However, as it happens, PHP's thread-safety is highly disputed. It's a use-if-you-really-really-know-what-you-are-doing ground.

    Final notes

    In case you are wondering, my personal advice would be to not use PHP in a multi-threaded environment if you have the choice!

    Speaking only of Unix-based environments, I'd say that fortunately, you only have to think of this if you are going to use PHP with Apache web server, in which case you are advised to go with the prefork MPM of Apache (which doesn't use threads, and therefore, PHP thread-safety doesn't matter) and all GNU/Linux distributions that I know of will take that decision for you when you are installing Apache + PHP through their package system, without even prompting you for a choice. If you are going to use other webservers such as nginx or lighttpd, you won't have the option to embed PHP into them anyway. You will be looking at using FastCGI or something equal which works in a different model where PHP is totally outside of the web server with multiple PHP processes used for answering requests through e.g. FastCGI. For such cases, thread-safety also doesn't matter. To see which version your website is using put a file containing <?php phpinfo(); ?> on your site and look for the Server API entry. This could say something like CGI/FastCGI or Apache 2.0 Handler.

    If you also look at the command-line version of PHP -- thread safety does not matter.

    Read the rest at the sourceFrom Stack Overflow: asked by O.., answered by Amr Mostafa (CC BY-SA 3.0)

  10. What is the difference between single-quoted and double-quoted strings in PHP?

    PHP strings can be specified not just in two ways, but in four ways.

    1. Single quoted strings will display things almost completely "as is." Variables and most escape sequences will not be interpreted. The exception is that to display a literal single quote, you can escape it with a back slash \', and to display a back slash, you can escape it with another backslash \\ (So yes, even single quoted strings are parsed).
    2. Double quote strings will display a host of escape sequences (including some regexes), and variables in the strings will be evaluated. An important point here is that you can use curly braces to isolate the name of the variable you want evaluated. For example let's say you have the variable $type and you want to echo "The $types are". That will look for the variable $types. To get around this use echo "The {$type}s are". Take a look at string parsing to see how to use array variables and such.
    3. Heredoc string syntax works like double quoted strings. It starts with <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. You don't need to escape quotes in this syntax.
    4. Nowdoc (since PHP 5.3.0) string syntax works essentially like single quoted strings. The difference is that not even single quotes or backslashes have to be escaped. A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. No parsing is done in nowdoc.

    Notes: Single quotes inside of single quotes and double quotes inside of double quotes must be escaped:

    $string = 'He said "What\'s up?"';
    $string = "He said \"What's up?\"";
    

    Speed:
    There is no difference.
    Please read a credible article on the matter from one of PHP core developers. Speaking of tests, one should never take them for granted. It must be understood that writing a credible test and, especially, interpreting its results requires a lot of knowledge and experience. Which means that most tests out there are just bogus. For example, in a code like this

    for($i=0;$i<100000;$i++) {
        'string';
    }
    

    The quoted string gets parsed only once, along with entire script, and then gets translated into opcode. Which is then gets executed a million times. So it measures anything but parsing. And that's only a tip of the iceberg. For a nanobenchmark like this, it's practically impossible to create a credible test that wouldn't be spoiled by some interfering side effect.

    From Stack Overflow: asked by rob waminal, answered by Peter Ajtai (CC BY-SA 4.0)

  11. How can I calculate the difference between two dates using PHP?

    Use this for legacy code (PHP < 5.3; Jun 2009). For up-to-date solution see jurka's answer.

    You can use strtotime() to convert two dates to Unix time and then calculate the number of seconds between them. From this, it's rather easy to calculate different time periods.

    $date1 = "2007-03-24";
    $date2 = "2009-06-26";
    $diff = abs(strtotime($date2) - strtotime($date1));
    $years = floor($diff / (365*60*60*24));
    $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
    $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
    printf("%d years, %d months, %d days\n", $years, $months, $days);
    

    Obviously, the preferred way of doing this is like described by jurka. My code is generally only recommended if you don't have PHP 5.3 or better.

    Several people in the comments have pointed out that the code above is only an approximation. I still believe that for most purposes that's fine, since the usage of a range is more to provide a sense of how much time has passed or remains rather than to provide precision. If you want to do that, just output the date.

    Despite all that, I've decided to address the complaints. If you truly need an exact range, but haven't got access to PHP 5.3, use the code below (it should work in PHP 4 as well). This is a direct port of the code that PHP uses internally to calculate ranges, with the exception that it doesn't take daylight savings time into account. That means that it's off by an hour at most, but except for that, it should be correct.

    Read the rest at the sourceFrom Stack Overflow: asked by gnanesh, answered by Emil H (CC BY-SA 4.0)

  12. When to use single quotes, double quotes, and backticks in MySQL?

    Backticks are to be used for table and column identifiers, but are only necessary when the identifier is a MySQL reserved keyword, or when the identifier contains whitespace characters or characters beyond a limited set (see below) It is often recommended to avoid using reserved keywords as column or table identifiers when possible, avoiding the quoting issue.

    Single quotes should be used for string values like in the VALUES() list. Double quotes are supported by MySQL for string values as well, but single quotes are more widely accepted by other RDBMS, so it is a good habit to use single quotes instead of double.

    MySQL also expects DATE and DATETIME literal values to be single-quoted as strings like '2001-01-01 00:00:00'. Consult the Date and Time Literals documentation for more details, in particular alternatives to using the hyphen - as a segment delimiter in date strings.

    So using your example, I would double-quote the PHP string and use single quotes on the values 'val1', 'val2'. NULL is a MySQL keyword, and a special (non)-value, and is therefore unquoted.

    None of these table or column identifiers are reserved words or make use of characters requiring quoting, but I've quoted them anyway with backticks (more on this later...).

    Functions native to the RDBMS (for example, NOW() in MySQL) should not be quoted, although their arguments are subject to the same string or identifier quoting rules already mentioned.

    Backtick (`)
    table & column ───────┬─────┬──┬──┬──┬────┬──┬────┬──┬────┬──┬───────┐
                          ↓     ↓  ↓  ↓  ↓    ↓  ↓    ↓  ↓    ↓  ↓       ↓
    $query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`, `updated`) 
                           VALUES (NULL, 'val1', 'val2', '2001-01-01', NOW())";
                                   ↑↑↑↑  ↑    ↑  ↑    ↑  ↑          ↑  ↑↑↑↑↑ 
    Unquoted keyword          ─────┴┴┴┘  │    │  │    │  │          │  │││││
    Single-quoted (') strings ───────────┴────┴──┴────┘  │          │  │││││
    Single-quoted (') DATE    ───────────────────────────┴──────────┘  │││││
    Unquoted function         ─────────────────────────────────────────┴┴┴┴┘    
    

    Variable interpolation

    The quoting patterns for variables do not change, although if you intend to interpolate the variables directly in a string, it must be double-quoted in PHP. Just make sure that you have properly escaped the variables for use in SQL. (It is recommended to use an API supporting prepared statements instead, as protection against SQL injection).

    // Same thing with some variable replacements
    // Here, a variable table name $table is backtick-quoted, and variables
    // in the VALUES list are single-quoted 
    $query = "INSERT INTO `$table` (`id`, `col1`, `col2`, `date`) VALUES (NULL, '$val1', '$val2', '$date')";
    

    Prepared statements

    When working with prepared statements, consult the documentation to determine whether or not the statement's placeholders must be quoted. The most popular APIs available in PHP, PDO and MySQLi, expect unquoted placeholders, as do most prepared statement APIs in other languages:

    // PDO example with named parameters, unquoted
    $query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`) VALUES (:id, :col1, :col2, :date)";
        
    // MySQLi example with ? parameters, unquoted
    $query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`) VALUES (?, ?, ?, ?)";
    

    Characters requring backtick quoting in identifiers:

    According to MySQL documentation, you do not need to quote (backtick) identifiers using the following character set:

    ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar, underscore)

    Read the rest at the sourceFrom Stack Overflow: asked by Nate, answered by Michael Berkowski (CC BY-SA 4.0)

  13. What is the best collation to use for MySQL with PHP?

    The main difference is sorting accuracy (when comparing characters in the language) and performance. The only special one is utf8_bin which is for comparing characters in binary format.

    utf8_general_ci is somewhat faster than utf8_unicode_ci, but less accurate (for sorting). The specific language utf8 encoding (such as utf8_swedish_ci) contain additional language rules that make them the most accurate to sort for those languages. Most of the time I use utf8_unicode_ci (I prefer accuracy to small performance improvements), unless I have a good reason to prefer a specific language.

    You can read more on specific unicode character sets on the MySQL manual - http://dev.mysql.com/doc/refman/5.0/en/charset-unicode-sets.html

    From Stack Overflow: asked by Darryl Hein, answered by Eran Galperin (CC BY-SA 3.0)

  14. Reference Guide: What does this symbol mean in PHP? (PHP Syntax)

    Incrementing / Decrementing Operators

    ++ increment operator

    -- decrement operator

    Example    Name              Effect
    ---------------------------------------------------------------------
    ++$a       Pre-increment     Increments $a by one, then returns $a.
    $a++       Post-increment    Returns $a, then increments $a by one.
    --$a       Pre-decrement     Decrements $a by one, then returns $a.
    $a--       Post-decrement    Returns $a, then decrements $a by one.
    

    These can go before or after the variable.

    If put before the variable, the increment/decrement operation is done to the variable first then the result is returned. If put after the variable, the variable is first returned, then the increment/decrement operation is done.

    For example:

    $apples = 10;
    for ($i = 0; $i < 10; ++$i) {
        echo 'I have ' . $apples-- . " apples. I just ate one.\n";
    }
    

    Live example

    In the case above ++$i is used, since it is faster. $i++ would have the same results.

    Pre-increment is a little bit faster because it really increments the variable and after that 'returns' the result. Post-increment creates a special variable, copies there the value of the first variable and only after the first variable is used, replaces its value with second's.

    However, you must use $apples--, since first, you want to display the current number of apples, and then you want to subtract one from it.

    You can also increment letters in PHP:

    $i = "a";
    while ($i < "c") {
        echo $i++;
    }
    

    Once z is reached aa is next, and so on.

    Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.

    Stack Overflow Posts:

    From Stack Overflow: asked by gooh, answered by Peter Ajtai (CC BY-SA 4.0)

  15. Deleting an element from an array in PHP

    There are different ways to delete an array element, where some are more useful for some specific tasks than others.

    Deleting a Single Array Element

    If you want to delete just one single array element you can use unset() and alternatively array_splice().

    By key or by value?

    If you know the value and don't know the key to delete the element you can use array_search() to get the key. This only works if the element doesn't occur more than once, since array_search() returns the first hit only.

    unset() Expression

    Note: When you use unset() the array keys won’t change. If you want to reindex the keys you can use array_values() after unset(), which will convert all keys to numerically enumerated keys starting from 0 (the array remains a list).

    Example Code:

    $array = [0 => "a", 1 => "b", 2 => "c"];
    unset($array[1]);
              // ↑ Key of element to delete
    

    Example Output:

    [
        [0] => a
        [2] => c
    ]
    

    array_splice() Function

    If you use array_splice() the (integer) keys will automatically be reindex-ed, but the associative (string) keys won't change — as opposed to array_values() after unset(), which will convert all keys to numerical keys.

    Note: array_splice() needs the offset, not the key, as the second parameter; offset = array_flip(array_keys(array))[key].

    Example Code:

    $array = [0 => "a", 1 => "b", 2 => "c"];
    array_splice($array, 1, 1);
                      // ↑ Offset of element to delete
    

    Example Output:

    [
        [0] => a
        [1] => c
    ]
    

    array_splice(), same as unset(), take the array by reference. You don’t assign the return values back to the array.

    Deleting Multiple Array Elements

    If you want to delete multiple array elements and don’t want to call unset() or array_splice() multiple times you can use the functions array_diff() or array_diff_key() depending on whether you know the values or the keys of the elements to remove from the array.

    array_diff() Function

    If you know the values of the array elements which you want to delete, then you can use array_diff(). As before with unset() it won’t change the keys of the array.

    Example Code:

    $array = [0 => "a", 1 => "b", 2 => "c", 3 => "c"];
    $array = array_diff($array, ["a", "c"]);
                             // └────────┘
                             // Array values to delete
    

    Example Output:

    [
        [1] => b
    ]
    

    array_diff_key() Function

    If you know the keys of the elements which you want to delete, then you want to use array_diff_key(). You have to make sure you pass the keys as keys in the second parameter and not as values. Keys won’t reindex.

    Example Code:

    Read the rest at the sourceFrom Stack Overflow: asked by Ben, answered by Konrad Rudolph (CC BY-SA 4.0)

  16. How do I get a YouTube video thumbnail from the YouTube API?

    Each YouTube video has four generated images. They are predictably formatted as follows:

    https://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg
    https://img.youtube.com/vi/<insert-youtube-video-id-here>/1.jpg
    https://img.youtube.com/vi/<insert-youtube-video-id-here>/2.jpg
    https://img.youtube.com/vi/<insert-youtube-video-id-here>/3.jpg
    

    The first one in the list is a full size image and others are thumbnail images. The default thumbnail image (i.e., one of 1.jpg, 2.jpg, 3.jpg) is:

    https://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg
    

    For the high quality version of the thumbnail use a URL similar to this:

    https://img.youtube.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg
    

    There is also a medium quality version of the thumbnail, using a URL similar to the HQ:

    https://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg
    

    For the standard definition version of the thumbnail, use a URL similar to this:

    https://img.youtube.com/vi/<insert-youtube-video-id-here>/sddefault.jpg
    

    For the maximum resolution version of the thumbnail use a URL similar to this:

    https://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg
    

    All of the above URLs are available over HTTP too. Additionally, the slightly shorter hostname i3.ytimg.com works in place of img.youtube.com in the example URLs above.

    Alternatively, you can use the YouTube Data API (v3) to get thumbnail images.

    From Stack Overflow: asked by CodeOverload, answered by Asaph (CC BY-SA 4.0)

  17. How can I prevent SQL injection in PHP?

    The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create an SQL statement with correctly formatted data parts, but if you don't fully understand the details, you should always use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.

    You basically have two options to achieve this:

    1. Using PDO (for any supported database driver):

      $stmt = $pdo->prepare('SELECT * FROM users WHERE name = :name');
      $stmt->execute([ 'name' => $name ]);
      foreach ($stmt as $row) {
          // Do something with $row
      }
      
    2. Using MySQLi (for MySQL):
      Since PHP 8.2+ we can make use of execute_query() which prepares, binds parameters, and executes SQL statement in one method:

      $result = $db->execute_query('SELECT * FROM users WHERE name = ?', [$name]);
      while ($row = $result->fetch_assoc()) {
          // Do something with $row
      }
      

      Up to PHP8.1:

      $stmt = $db->prepare('SELECT * FROM employees WHERE name = ?');
      $stmt->bind_param('s', $name); // 's' specifies variable type 'string'
      $stmt->execute();
      $result = $stmt->get_result();
      while ($row = $result->fetch_assoc()) {
          // Do something with $row
      }
      

    If you're connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, pg_prepare() and pg_execute() for PostgreSQL). PDO is the universal option.

    Correctly setting up the connection

    PDO

    Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:

    $dsn = 'mysql:dbname=dbtest;host=127.0.0.1;charset=utf8mb4';
    $dbConnection = new PDO($dsn, 'user', 'password');
    $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    

    In the above example, the error mode isn't strictly necessary, but it is advised to add it. This way PDO will inform you of all MySQL errors by means of throwing the PDOException.

    What is mandatory, however, is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).

    Although you can set the charset in the options of the constructor, it's important to note that 'older' versions of PHP (before 5.3.6) silently ignored the charset parameter in the DSN.

    Mysqli

    For mysqli we have to follow the same routine:

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // error reporting
    $dbConnection = new mysqli('127.0.0.1', 'username', 'password', 'test');
    $dbConnection->set_charset('utf8mb4'); // charset
    

    Explanation

    Read the rest at the sourceFrom Stack Overflow: asked by Andrew G. Johnson, answered by Theo (CC BY-SA 4.0)

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.