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条)

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备