Nolski
Nolski

Reputation: 443

Using strings as an array index PHP

I'm really stumped on this one. I have this array variable $banner_image_description. When I print it I get Array ( ['title'] => dafha ['price'] => adhfadhf ).

Now, what I'm trying to do is check the length of the value at 'title' and make sure it is more than 2. So when I run :

if (isset($this->request->post['banner_image'])) 
    {
        foreach ($this->request->post['banner_image'] as $banner_image_id => $banner_image) 
        {
            foreach ($banner_image['banner_image_description'] as $language_id => $banner_image_description) 
            {   
                print_r($banner_image_description);
                echo('<br/>');
                if ((utf8_strlen($banner_image_description['title']) < 2) || (utf8_strlen($banner_image_description['title']) > 64)) 
                { 

                    $this->error['banner_image'][$banner_image_id][$language_id] = $this->language->get('error_title'); 
                }                   
            }
        }   
    }

I get Notice: Undefined index: title and I have no idea why. I thought this was the correct way to go about getting the value at 'title' and I know the index is there and the value is there.

I am pretty sure that the array is being populated by POSTing form values:

if (isset($this->request->post['banner_image'])) 
{
    $banner_images = $this->request->post['banner_image'];
}

Here is what the form values look like:

<input type="text" 
 name="banner_image[<?php echo $image_row; ?>][banner_image_description][<?php echo $language['language_id']; ?>]['title']" 
 value="<?php echo isset(
 $banner_image['banner_image_description'][$language['language_id']]['title']) ? 
 $banner_image['banner_image_description'][$language['language_id']]['title'] : ''; ?>" />
 <img src="view/image/flags/<?php echo $language['image']; ?>" title="<?php echo $language['name']; ?>" /><br />

Upvotes: 0

Views: 168

Answers (2)

Nolski
Nolski

Reputation: 443

var_dump() revealed that the key is including ' So the if statement should be set to

if ((utf8_strlen($banner_image_description["'title'"]) < 2) || (utf8_strlen($banner_image_description["'title'"]) > 64))

Upvotes: 0

Miverson
Miverson

Reputation: 143

That is a warning, it is poor programming but will not break anything yet.

Do this, it will make sure the key is set and has a value. Keep in mind if this is not set so the key has no value, your echo statement will not trigger.

if (isset($banner_image_description['title']) && (utf8_strlen($banner_image_description['title']) < 2)) 
{ 
    echo 'too short!';
}

Upvotes: 1

Related Questions