Home  >  Article  >  Backend Development  >  PHP replaces an array information

PHP replaces an array information

王林
王林Original
2023-05-07 13:41:08358browse

In PHP, we often need to add, delete, modify, and check arrays. Replacing a piece of information in an array is also a relatively common operation.

Below we will use an example to explain how to replace an array information in PHP.

Suppose we have an array $user_info, which stores several personal information, including name, age, occupation and other information. Now we need to replace the information of one of the users, for example, replace the occupation of a user who is 25 years old as a programmer:

$user_info = array(
    0 => array(
        'name' => '张三',
        'age' => 23,
        'profession' => '设计师'
    ),
    1 => array(
        'name' => '李四',
        'age' => 25,
        'profession' => '销售员'
    ),
    2 => array(
        'name' => '王五',
        'age' => 30,
        'profession' => '教师'
    )
);

// 遍历数组查找需要替换的用户
foreach ($user_info as $key => $user) {
    // 根据年龄为 25 岁查找需要替换的用户
    if ($user['age'] == 25) {
        // 替换该用户的职业
        $user_info[$key]['profession'] = '程序员';
        break;
    }
}

// 输出替换后的用户信息
print_r($user_info);

In the above code, we use a foreach loop to traverse the array, and according to the age of 25 Find the user who needs to be replaced. After finding the user, use the array subscript to replace the user's occupation, and use the break statement to jump out of the loop to improve code efficiency.

Finally, we use the print_r() function to output the replaced user information. The output result is as follows:

Array
(
    [0] => Array
        (
            [name] => 张三
            [age] => 23
            [profession] => 设计师
        )

    [1] => Array
        (
            [name] => 李四
            [age] => 25
            [profession] => 程序员
        )

    [2] => Array
        (
            [name] => 王五
            [age] => 30
            [profession] => 教师
        )

)

It can be seen from the output result that the occupation of the 25-year-old user has been successfully changed to programmer.

In summary, replacing a certain piece of information in the array requires traversing the array to find the information that needs to be replaced, and using the array subscript to replace the corresponding value. Using the break statement can improve code efficiency and avoid traversing the entire array.

The above is the detailed content of PHP replaces an array information. For more information, please follow other related articles on the PHP Chinese website!

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