PHP uses a foreach loop to iterate through the array, and the loop executes successfully, but the loop is not successful? -Segmentfault

Source: Internet
Author: User
Keywords Php foreach
Tags button type
            foreach($arr as $value){                $value=preg_replace("/href=\"\//i",'href="'.$link,$value);                echo $value."
";//此处$value为替换之后的值。 } echo $arr[1];//此处显示的仍为替换前$arr[1]的值。//请问这个是怎么回事呢?``

Reply content:

            foreach($arr as $value){                $value=preg_replace("/href=\"\//i",'href="'.$link,$value);                echo $value."
";//此处$value为替换之后的值。 } echo $arr[1];//此处显示的仍为替换前$arr[1]的值。//请问这个是怎么回事呢?``

    • 38 minutes ago Question
    • Comments
    • Invitation to answer

Please login and comment first

Sort By default sorting time

4 answers

The answer is helpful to the person, has the reference value 0 The answer is no help, it's the wrong answer, irrelevantly replying .

foreach($arr as &$value){    $value=preg_replace("/href=\"\//i",'href="'.$link,$value);    echo $value."
";//此处$value为替换之后的值。}echo $arr[1];//此处显示的仍为替换前$arr[1]的值。

Because of the scope of the variable, if you modify the value inside, and you need to save the result, you need to define the type as a reference type , that is & .

Change it.

        foreach($arr as $key=>$value){            $arr[$key]=preg_replace("/href=\"\//i",'href="'.$link,$value);            echo $arr[$key]."
";//此处$value为替换之后的值。 }

You just did a replace operation on the local variable $value in the loop, and did not return the value to $arr.

foreach($arr as $key => $value){    $value=preg_replace("/href=\"\//i",'href="'.$link,$value);    $arr[$key] = $value;    echo $value."
";//此处$value为替换之后的值。}echo $arr[1];//此处显示的仍为替换前$arr[1]的值。

Get it straight, pass it by value, and pass it by reference.

  • 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: info-contact@alibabacloud.com 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.