Steve Fischer
Steve Fischer

Reputation: 325

php variable in array problem

whats wrong with this picture?

$appleVar = 'apple';
$veggie = 'carrots';

$var = array('fruit' => $appleVar, 'veggie' => ''.$carrotVar.' no carrots please');

print_r($var);

when I print the array only "no carrots please" is displayed. why?

I'm so sorry I meant

$carrotVar = 'carrots'; not $veggie = 'carrots';

Upvotes: 1

Views: 1239

Answers (6)

Ruben
Ruben

Reputation: 9186

$appleVar = 'apple';  
$veggie = 'carrots';  
$carrotVar = $veggie . ' no carrots please';  
$var = array('fruit' => $appleVar, 'veggie' => $carrotVar);  

(or whatever your output needs to be.)

Upvotes: 0

dejavu
dejavu

Reputation: 19

Although php doesn't need variable declaration, you can simply use it just by defining it when needed by the variable you are using, i.e. $carrotVar has no value in it so the output is being displayed not as you wished just switch $veggie = 'carrots'; to $carrotVar = 'carrots'; or change the array variable.

Upvotes: 1

gmadd
gmadd

Reputation: 1156

change

$veggie = 'carrots';

to

$carrotVar = 'carrots';

Upvotes: 2

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

You did not define $carrotVar.

Upvotes: 0

Jatin Dhoot
Jatin Dhoot

Reputation: 4364

Have you checked carefully.

In my case it is printing :-

Notice: Undefined variable: carrotVar in /home/jatin/webroot/vcms/trunk/application/modules/ibroadcast/controllers/VideoController.php on line 10 Array (
    [fruit] => apple
    [veggie] =>  no carrots please )

Upvotes: 1

Pascal MARTIN
Pascal MARTIN

Reputation: 401032

When declaring the array, you are using $carrotVar :

$var = array(
    'fruit' => $appleVar, 
    'veggie' => ''.$carrotVar.' no carrots please'
);

But that $carrotVar variable is not defined.


You should probably use the $veggie variable :

$var = array(
    'fruit' => $appleVar, 
    'veggie' => ''.$veggie.' no carrots please'
);


Or rename it so it matches its content :

$carrotVar = 'carrots';

Upvotes: 1

Related Questions