search
HomeBackend DevelopmentPHP Tutorial[Happy 100 days of learning PHP] Day two: Crazy array_PHP tutorial

Link to the previous issue: Happy 100 days of learning PHP, the first day

This issue’s motto:
Why do some people always feel that when learning PHP, they learn some knowledge points very well and others but never learn it? It is because the facial muscles are too tense when learning, which leads to necrosis of nerve endings, so they are lame.
Knowledge point in this issue: php array
Arrays are the most iconic tool function of PHP. If you learn PHP arrays well, you will basically have the initial capital to get involved in the PHP world.
I once had a friend who opened a computer company. Generally, the main business of computer companies is to sell computers, and occasionally provide some spare parts. Of course, depending on the situation, some companies also sell some CDs, such as movies, games, etc. My friend who is more technical is also a grassroots programmer, and he despises the act of selling CDs, especially CDs from island countries. For a long time in the early days, his main business was helping some companies or enterprises to build websites. Promotional websites at that time were not as complicated as they are now. They basically only had 2-3 pages. Dynamic websites would have no more than 10 interfaces. What’s more, there was a lot of free space at the time, so it was easy for him to earn hundreds of dollars at that time. , very agile and efficient. I once "stole" his website code. I can't remember all of it. I can only give a rough outline of it. You can take a look at it. PHP:
[php] view plaincopy
$var=file("./product list.txt");//It was better to use txt than access at that time
if(!$var || is_array($var) || count($var)==0) exit("The system is busy, please try again later");
$fix=array("China's largest XXX website", "Only our products are authentic", "Fake ones and fined ten for fakes will never cheat people", "Where can I buy such good XXX? Don't hesitate anymore "");
?>
<?php echo $fix[0]?>
//Note that 800*600 was the national standard at that time, don’t think too much


?

....This is a mess of fake Godly sentences...
....Here are advertisements interspersed by similar websites that support each other, such as: "Stir up the tiger in you" or "My legs and feet are healed after using XXX, but I can't afford it." It’s night” and so on.
echo '
  • '.$eachline.'
  • ';
    //The title of the product is very sensational, which means if you don’t buy it, you will regret your trip to this world.
    ?>
    ........Note that this is already the end of the page... //Note that the filing was really not strict at that time
                                                                         
    //Note that my friend did not know how to script at the time, so the page had to be refreshed once before the current time would change.
    Okay, the above is a basic skill that my friend relies on to survive. It is said that for a customer of the same type, he only needs to change the content of "Product List.txt" and then replace the background image of td, and the page will immediately get a new look. My friend told me very seriously at that time that he had achieved "productization" ” development model. I admire it so much because when I first learned ASP, it was definitely not so "configurable".
    Don’t be too entangled with the advertisements and statements in the webpage. Anyway, as a novice, I saw this webpage and wanted to spend money to give it a try, but my friend told me that I was not ready to use it yet. I asked "when can it be used", and my friend "slapped" me.
    Next, let’s get to the point and explain the above knowledge points.
    1. The most basic form of expression of array
    $fix=array("Content1","Content2","Content3"); This is the most basic way of expressing PHP arrays. Please forgive me for not typing the ad again, it's too disgusting.
    You can accumulate as much content as you want, as long as you can write it. When you want to call the content inside, you just need to start counting from "0", such as $fix[0], $fix[1]...$fix[n].
    Note: Why start from 0. One is because "php boss" designed it this way, and the other is because the true form of this most basic array is
    $fix=array(0=>"Content1",1=>"Content2",2=>"Content3");
    The symbol "=>" is omitted. The left side of this symbol is the key and the right side is the value. Generally, many textbooks will explain it as "$key=>$value". Don't worry about why the left side is $key. The right side is $value. I tell you that it is a customary way of writing. You have to write it as $ss=>$bb, which means that the one on the left is the key and the one on the right is the value.
    So: any form of array will have keys and values. Whether you omit it or not is up to you. Regardless of whether you omit it or not, I did it anyway.
    Expand a bit: Since there is a key value, you can change the key value.
    For example $fix=array("Exaggerated website name" => "China's largest XXX website", "Bullshit product brand" => "Only we are the most authentic", "I feel like vomiting after hearing this Advertising slogan"=>"One false penalty and ten penalty will never deceive people");
    If you want to output the "bullshit product brand" to the page at this time, you cannot use echo $fix[1]; because the key value has been changed by you.
    You should use echo $fix['Bullshit product brand'];
    2. Traverse the array
    Continue to use $fix=array("Content1", "Content2", "Content3"); as an example
    1. Using foreach is the most suitable and suitable method for looping small arrays.
    The basic syntax is: foreach (here is the original array as here is the variable set each time it is traversed)
    For example: foreach($var as $eachline) echo $eachline; will output content 1...content 3;
    2. Many people know that there is actually a while that can traverse an array
    The basic syntax is: while(list($key,$value)=each($attr))
    For example: while(list($key,$value)=each($fix)) echo $key.$value; will output 0 content 1. in sequence. . . . 2 Content 2;
    The difference between these two types of traversal will not be discussed too deeply here. It will be discussed later. I will only tell you now that if you just want to traverse data, then use foreach at any time. If you want to change the value of the array while iterating, use while. There is only one word for the reason, for "fast". Nowadays, the pace of life is too fast, and the first principle of writing programs is "fast".
    As for other syntaxes for traversing arrays, I personally think there is no need to learn them, unless you are going to take the exam. If it is actual combat, these two are enough, and we also want to be fast.
    To expand, the values ​​in the array can not only contain strings, but also arrays or any form of variable values.
    For example, $fix=array("Bullshit advertising slogans"=>array("The first 100 people who order will get another 200 yuan gift package", "Proficient in a certain language in 20 days", "Children don't eat because of lack of food" X"));
    For such an array, the value of $fix['Bullshit advertising words'] is actually an array,
    For example, echo $fix['Bullshit advertising slogan'][1]; will output "Master a language in 20 days"
    3. Assignment of arrays
    Let’s give an example:
    $fix=array(); This array is empty.
    $fix[]="Content 1"; This is equivalent to $fix=array("Content 1"); or $fix=array(0=>"Content 1");
    $fix[]="Content2"; This is equivalent to $fix=array("Content1","Content2"); or $fix=array(0=>"Content1",1= >"Content 2");
    $fix['What are we learning']='php'; This is equivalent to $fix=array(0=>"Content 1","What are we learning"=>"php");
    The above assignments are all assigned at the end of the array. In fact, there is also the array_push function that can assign values. The syntax is $fix=array_push($fix,"Content1","Content2"); The effect is the same, except array_push You can add multiple values ​​at once, one at a time using '[]'.
    PHP array functions are very powerful. You can do almost anything you want to do, such as sorting, merging, reversing, deleting, etc. of arrays. You can search on Baidu. Due to space issues, I won’t go into details here. I’ll just use the functions back and forth. , not difficult. However, when it comes to actual projects, a lot of data processing needs to be done through database stored procedures, optimized table structures, good data sorting algorithms, and skilled data reading methods. In actual practice, many array functions in PHP are basically For example, if you receive a project like 1230X and want to list and sort the names of all Chinese people, do you dare to use a php array to traverse, merge, and reverse? Of course, if your customers are for the Vatican or Iceland, you can do this.
    However, there are many functions such as is_array--whether it is an array, in_array---whether a certain value exists, array_key_exists---whether a certain key value exists in the array, etc. Common functions must be learned. If you can't learn it, then you are not far away from becoming a leader.
    Easter egg:
    There is $var=file("./product list.txt"); above, which means that the text document is read at one time and read into an array line by line, including line breaks.

    www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477566.htmlTechArticle Previous issue link: Happy 100 days of learning PHP, the first day. This issue’s motto: Why do some people always feel good when learning PHP? I learned some knowledge points very well, but I still couldn't learn them. That's because my face was on my face when I was learning...
    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

    Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

    How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

    Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

    What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

    Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

    How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

    Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

    What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

    The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

    How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

    Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

    What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

    SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

    How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

    Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    SublimeText3 Linux new version

    SublimeText3 Linux new version

    SublimeText3 Linux latest version

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)