3

I have the following error;

Note: Array to string conversion in [file_path] on line 919

which relates to this line of code where I'm trying to assign this string as a value in an array

$contents[11] = "$hours:$minutes:$seconds\n$ca_1[remaining_time]\n$h:$m:$s";

Why am I getting this error, and how do I resolve it?

Andle
  • 195
  • 13
  • Your questions appears to be ambiguous . Please make it clear – TheVigilant Dec 26 '15 at 14:01
  • that is `Note` not error, it seems. it is a literal string or you need to evaluate variables inside that string ? use single quote `'` for literal. one of the variable inside is array. most probably `$ca_1`, use it like alexander suggested, `$ca_1['remaining_time']`. – Jigar Dec 26 '15 at 14:02

2 Answers2

3

It's a bad practice to interpolate string this way because it makes the code very difficult to read, so you should rather use "{$h}" instead of "$h".

As Terminus mentioned in comments, depending on the PHP version,

echo "$ca_1[remaining_time]"

Does not necessarily give a

PHP Notice: Use of undefined constant

Like echo $ca_1[remaining_time] would. But since that didn't work for you, you'd better quote that like ['remaining_time'].

You might also find some interesting things on this topic here.

Second, use curvy braces to explicitly tell what you want to insert:

$contents[11] = "$hours:$minutes:$seconds\n{$ca_1['remaining_time']}\n$h:$m:$s";

This really improves readability.

Community
  • 1
  • 1
Alexander Mikhalchenko
  • 4,525
  • 3
  • 32
  • 56
  • Using associative arrays in double quoted strings like: `[remaining_time]` doesn't cause an error whenever I use it. –  Dec 26 '15 at 14:48
  • @Terminus yes, because it attempts to find a constant with such name, and when it fails, it takes it's string value. That also gives a *Notice: Use of undefined constant*. – Alexander Mikhalchenko Dec 26 '15 at 14:50
  • 1
    I should've done the full `"$ca_1[remaingingTime]"` That works to access array elements. Php v5.4 and 5.6 –  Dec 26 '15 at 14:52
  • @Terminus, yeah, my bad, ``"$ca_1[remaingingTime]"`` does not give a notice – Alexander Mikhalchenko Dec 26 '15 at 15:06
1

Try:

$contents[11] = $hours . ':' . $minutes . ':' . $seconds + "\n" . $ca_1['remaining_time'] . "\n " . $h . ':' . $m . ':' . $s";

If this still fails, check your variables. Maybe one of them is an array!?

chickahoona
  • 1,914
  • 14
  • 23