Undefined Index of array [closed]
-
01-06-2021 - |
Question
I'm trying to figure out why I'm getting an undefined index in the view for this line:
<?php if ($allies[''] == 'No Wrestlers In Database') {
Controller:
if (empty($rosterList)) {
$allies[] = 'No Wrestlers In Database';
}
else
{
$allies[] = 'Please Select An Option';
foreach ($rosterList AS $ally)
{
$allies[$ally->id] = $ally->rosterName;
}
}
View:
<?php if ($allies[''] == 'No Wrestlers In Database') {
echo $allies[''];
}
else {
echo form_dropdown( 'ally1', $allies, $alliesList->ally1ID);
} ?>
EDIT :
I'm trying to figure out why my first dropdown isn't showing the correct value. alliesList print_r
Array
(
[0] => stdClass Object
(
[id] => 1
[rosterListID] => 1
[ally1ID] => 2
[ally2ID] => 3
[ally3ID] => 2
[ally4ID] => 3
[ally5ID] => 2
)
)
allies print_r
Array
(
[0] => Please Select An Option
[1] => Kid Wonder
[3] => Oriel
[2] => Test Character
)
EDIT 2:
Here's what I made it but getting an error in my view file that says trying to get property of non object.
//Get member's allies
$alliesList = $this->bios->getRosterAlliesByRosterID($this->session->userdata('defaultRosterListID'));
echo "<pre>";
print_r($alliesList);
echo "</pre>";
// Get list of members
$rosterList = $this->bios->getAllRoster();
$allies = array();
if (empty($rosterList)) {
$allies[''] = 'No Wrestlers In Database';
}
else
{
$allies[''] = 'Please Select An Option';
foreach ($rosterList AS $ally)
{
$allies[$ally->id] = $ally->rosterName;
}
}
echo "<pre>";
print_r($alliesList);
echo "</pre>";
<?php echo form_label( 'Ally 1', 'ally1'); ?>
<div>
<?php if (in_array('No Wrestlers In Database', $allies)) {
echo 'No Wrestlers In Database';
}
else {
echo form_dropdown( 'ally1', $allies, $alliesList->ally1ID);
} ?>
</div>
Solution
Because when assigning, the assignment index is incremented from 0 to n in arrays. So, you'll need this:
if ($allies[0] == 'No Wrestlers In Database')
OTHER TIPS
Using $arr[] does not creates value for key '', but push element at array tail.
You are misunderstand about array declaration.
$allies[''] is not equal to $allies[]
$allies[], is use for append your object to the end of array. the key will auto increment.
$allies[''], this one, '' is a string, so, your value will save to array with key ''
you can read more about key of array here
The key can either be an integer or a string. The value can be of any type.
Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.
Null will be cast to the empty string, i.e. the key null will actually be stored under "".
If you really want it to display, you may change your controller $allies[] to $allies['']
If you want to see if 'No Wrestlers In Database' is in your array, you have to use in_array() function.