Jump to content

PHP 5 array and String Offsets


beifler

Recommended Posts

Greetings,

I have an array to output a dropdown menu from a database that fails with the error "Cannot use string offset as an array". I'm using PHP 5 and I'm not sure how to change the function to be compatible.

Here's the string: 
[code]function tep_get_source_list($name, $show_other = false, $selected = '', $parameters = '')[/code]

"[b]$show_other = false[/b]" is the offender.  When I remove it, the string offset error goes away.


The intent of this function is to populate a dropdown menu with mySQL data for people to select which search engine they came from, or choose "other" to enter the information into a text field. 
Here's the main (error generating) code:

[code]  function tep_get_source_list($name, $show_other = false, $selected = '', $parameters = '') {
   
    $sources_array = array(array('id' => '', 'text' => PULL_DOWN_DEFAULT));
    $sources = tep_get_sources();

    for ($i=0, $n=sizeof($sources); $i<$n; $i++) {
      $sources_array[] = array('id' => $sources[$i]['sources_id'], 'text' => $sources[$i]['sources_name']);
    }

    if ($show_other == 'true') {
    $sources_array[] = array('id' => '9999', 'text' => PULL_DOWN_OTHER);
    }

    return tep_draw_pull_down_menu($name, $sources_array, $selected, $parameters);
  }
[/code]

I also found this in the php.net's "PHP5 Backward Incompatible Changes" ( http://www.php.net/manual/en/migration5.incompatible.php )
"Illegal use of string offsets causes E_ERROR instead of E_WARNING.

An example illegal use is:

[code]$str = 'abc'; unset($str[0]);.[/code]

How can "$show_other = false" be used compatibly?

Help is much apreciated
Link to comment
https://forums.phpfreaks.com/topic/26646-php-5-array-and-string-offsets/
Share on other sites

The error occurs when you try to use a string as if it was an array.

If the error occurs within tep_get_source_list() itself, then it must occur in this line:

[code]$sources_array[] = array('id' => $sources[$i]['sources_id'], 'text' => $sources[$i]['sources_name']);[/code]

And the cause would be that $sources, as returned from tep_get_sources(), is not the type of array that was expected.  Try var_dump($sources) before the for loop, and see if it looks unusual.

If $sources is fine, then the error may be occurring in a function called by tep_get_source_list().
This is a strange one; if I add "$id" to [code]return tep_draw_pull_down_menu($name, $id, $sources_array, $selected, $parameters);[/code] everything works.  I don't know why though, and I don't understand the structure enough to figure it out.
But it works!

Thanks for your help btherl!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.