dongzhankou2090 2015-07-19 04:39
浏览 30
已采纳

PHP数组分配值然后获取变量值

I'm sorry for this beginner question. My problem is that I would like to get the value of the variable name assigned in the array. For instance like this:

$fruits = array($apple, $mango, $banana);

And then I am assigning the elements in the array same values.

for ($i = 0; $i < count($fruits); $i++) { 
    $fruits[$i] = "fruit";
}

When I want to print the apple value in the array I would do:

echo $fruits[0];

But what I want is that to print the value of apple in the array using:

echo $apple;

How would I do this? Sorry beginner here..

  • 写回答

2条回答 默认 最新

  • duanchun1881 2015-07-19 05:04
    关注

    Ok,so what you are doing is incorrect to begin with.

    $apple = "apple";
    $mango = "mango";
    $banana ="banana";
    
    $fruits = array($apple, $mango, $banana);
    
    for ($i = 0; $i < count($fruits); $i++) { 
        $fruits[$i] = "fruit";
    }
    echo "<pre>";
    print_r($fruits);
    

    What you have done in your for loop is to override the values of the array. So when you do the print_r you will get:

    Array
    (
        [0] => fruit
        [1] => fruit
        [2] => fruit
    )
    

    If you want to store whether it is a fruit or vegetable (and i wonder if it is the case, since your array name is 'fruits'), however if you do want to do that, then you should use an associative array:

     $cabbage= 'cabbage';
     $stuffIEat = array($apple => 'fruit', 
                        $mango => 'fruit', 
                        $banana =>'fruit',
                        $cabbage => 'vegetable');
    

    Now when you want to see what kind of stuff apple is, you do:

    echo $stuffIEat[$apple]; //prints fruit
    echo $stuffIEat[$cabbage]; //prints vegetable
    

    Now if you want to print all the fruits that you eat, you do:

    print_r(array_keys($stuffIEat,'fruit'));

    This will print

    Array
    (
        [0] => apple
        [1] => mango
        [2] => banana
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?