Jump to content

illegal string offset


codingcasually
Go to solution Solved by Barand,

Recommended Posts

I am writing a script that downloads stock data and graphs the prices using libchart charting library. After downloading data to array $prices, I use the following line to add a new data point to my chart:

 

$serie1->addPoint(new Point($prices[$i]['date'], $prices[$i]['price']);

 

$prices contains both date and price keys. However, this throws off illegal string offset error for both keys. I have checked with isset, both variables contain values. I have also tried typecasting, date with (string) and price with (float), but these threw off new errors.

 

What could be causing the illegal string offset error? Is there a way to silence it?

Edited by codingcasually
Link to comment
Share on other sites

Are you sure $prices and $prices[$i] are arrays?

Check with is_array(). This 'illegal string offset' error often happens when someone tries to access a string as if it was an array.

 

You could try something like:

if (!is_array($prices)) 
  trigger_error('$prices is NOT an array!', E_USER_ERROR);

if (!is_array($prices[$i])) 
  trigger_error('$prices[$i] is NOT an array!', E_USER_ERROR);

... your code here ...

You should never 'silence' errors. This is done only by lazy programmers that doesn't care about doing their job correctly. A good programmer should find where the error comes from, understand it and make it disappear by using proper code (except in sore rare occurrences where it's OK to silence an error: a bug that you can't correct from PHP or an external library, which is uncommon).

Link to comment
Share on other sites

@mogosselin: Yes, it is an array as verified by is_array(), plus I've used the price key in some functions in the same code prior to the 1 specified above without any problems. Je n'ai aucune idee, pourquoi il ne marche pas. Merci beaucoup.

 

@daviddannis: The indices are correct, and I have previously used print_r as well as isset() to verify that the array values are set and correct. Thanks for the suggestion though.

Link to comment
Share on other sites

@quickoldcar: My mistake, I missed a ) transcribing to my post, the original did have it, php would've caught it otherwise. Thanks.

 

@barand: the first part of the code pulls 2-month stock price data from yahoo finance csv, and populates date and open, high, low, close price keys correspondingly (above snippet uses close). Here's gist of (not very cleanly-written) code:

 

$url = 'http://real-chart.finance.yahoo.com/table.csv?s='.'KO'.'&a='.$prevmonth.'&b='.$prevday.'&c='.$prevyear.'&d='.$curmonth.'&e='.$curday.'&f='.$curyear.'&g=d&ignore=.csv'; //'KO' refers to ticker symbol of Coca Cola
$handle = fopen($url, "r");
$arr['filesize'] = sizeof($handle);
$keys = array('line', 'date', 'open', 'high', 'low', 'close', 'volume', 'adj');
//new keys
$arr = array();
$buffer = fgets($handle, 5120);
if ($buffer == "")
return false;
//parse each line and place into array $one
while (($buffer = fgets($handle, 5120)) !== false) {
if (!preg_match('/([0-9\-]{10})[\,]{1}([0-9\.]+)[\,]{1}([0-9\.]+)[\,]{1}([0-9\.]+)[\,]{1}([0-9\.]+)[\,]{1}([0-9\.]+)[\,]{1}([0-9\.]+)\s?/', $buffer, $one))
return false;
$one = array_combine($keys, array_values($one)); //rekeying
$rawdata[] = $one;
}

if (!feof($handle))
        {
        echo "Error: unexpected fgets() fail\n";
        return false;
        }
    fclose($handle);
    for ($i=0; $i<sizeof($rawdata); $i++)
        {
        $dataarray[$i]['date']=$rawdata[$i]['date'];
        $dataarray[$i]['high']=$rawdata[$i]['high'];
        $dataarray[$i]['low']=$rawdata[$i]['low'];
        $dataarray[$i]['close']=$rawdata[$i]['close'];
        }
     $prices = (array_reverse($dataarray));//flip price array order

 

the charting code comes straight from libchart documentation, which plots daily closing prices (Y axis) and trading date (X axis):

 

$chart1 = new LineChart();//start macdchart
    $serie1 = new XYDataSet();
    $chart2 = new LineChart();
    $serie2 = new XYDataSet();
    $serie3 = new XYDataSet();
    for ($i=25; $i<sizeof($prices); $i++)
        {
        $serie1->addPoint(new Point($prices[$i]['date'], $prices[$i]['close']);
        }

 

Hope this is enough detail. Thanks.

Link to comment
Share on other sites

@barand: Dude, you know what, I made a dumb mistake, I did a print_r previously but didn't scroll all the way down to see all 43 entries. I followed your advice with var_export (output the same array) but this time I noticed my final was messed up, I tacked on a metric I calculated that resulted in the error.

 

Thanks for your help!

Edited by codingcasually
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.