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..
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
)
This is an alternative.
<?php
$fruits = array(
"apple" => $apple,
"mango" => $mango,
"banana" => $banana);
foreach ($fruits as $key => $value) {
$fruits[$key] = "fruit";
}
echo $fruits['mango'];