Reputation: 1311
Why is it that when I setup an array like this:
$plans[] = array(
'provider' => 'Boost Mobile',
'plan' => 'Unlimited Gigs',
'url' => 'https://www.boostmobile.com/#!/shop/plans/monthly-phone-plans/',
'price' => 50,
'duration' => 'month',
}
I get an arror if I echo out a key like this:
echo $plans['plan'];
//Notice: Undefined index: plan
BUT when I echo it out inside a foreach array it outputs the value?
Any help is appreciated
Upvotes: 0
Views: 97
Reputation: 1303
You are actually just adding another element (which is, in this case, an array) to an existing array called $plans if you want to define an array $plans use this
$plans = array(
'provider' => 'Boost Mobile',
'plan' => 'Unlimited Gigs',
'url' => 'https://www.boostmobile.com/#!/shop/plans/monthly-phone-plans/',
'price' => 50,
'duration' => 'month',
}
So now you can retrieve the value of the key 'plan' from your $plans array with this line
echo $plans['plan'];
Upvotes: 1
Reputation: 4166
You have define $plan
with array so no need to take []
with $plans
because it create multi dimentional array.
I have added both example with and without []
.
Note
$plans[] = array(); // It creates multi dimensional array
$plans = array(); // It creates simple array
Code
<?php
$plans[] = array(
'provider' => 'Boost Mobile',
'plan' => 'Unlimited Gigs',
'url' => 'https://www.boostmobile.com/#!/shop/plans/monthly-phone-plans/',
'price' => 50,
'duration' => 'month');
print_r($plans);
echo $plans[0]['plan']; echo "\n\n";
$plans2 = array(
'provider' => 'Boost Mobile',
'plan' => 'Unlimited Gigs',
'url' => 'https://www.boostmobile.com/#!/shop/plans/monthly-phone-plans/',
'price' => 50,
'duration' => 'month');
print_r($plans2);
echo $plans2['plan'];
Output
Array
(
[0] => Array
(
[provider] => Boost Mobile
[plan] => Unlimited Gigs
[url] => https://www.boostmobile.com/#!/shop/plans/monthly-phone-plans/
[price] => 50
[duration] => month
)
)
Unlimited Gigs
Array
(
[provider] => Boost Mobile
[plan] => Unlimited Gigs
[url] => https://www.boostmobile.com/#!/shop/plans/monthly-phone-plans/
[price] => 50
[duration] => month
)
Unlimited Gigs
Check Demo : Click Here
Upvotes: 1
Reputation: 8249
$plans
is a two-dimensional array. If you want to show plan
, you need to use give the first dimension too, which is 0 in your case.
print_r($plans);
Array
(
[0] => Array
(
[provider] => Boost Mobile
[plan] => Unlimited Gigs
[url] => https://www.boostmobile.com/#!/shop/plans/monthly-phone-plans/
[price] => 50
[duration] => month
)
)
And here is what echo
would give you:
echo $plans[0]['plan'];
Unlimited Gigs
Click here for demo: https://3v4l.org/Ytk79
Upvotes: 1
Reputation: 6311
if it is $plans[]
then you should do this
echo $plans[0]['plan'];
if it is $plans
then it will be
echo $plans['plan'];
Upvotes: 0
Reputation: 2327
You are adding an array at $plans[0].
So your value is as follows.
$plans[0]['plan'];
You can view full array by this
echo "<pre>"; print_r($plans);
Upvotes: 0