Andle
Andle

Reputation: 195

How to assign a string value to an index of php array?

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?

Upvotes: 3

Views: 1347

Answers (2)

chickahoona
chickahoona

Reputation: 2034

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!?

Upvotes: 1

Alexander Mikhalchenko
Alexander Mikhalchenko

Reputation: 4565

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.

Upvotes: 3

Related Questions