-1

I'm trying to add an array element so that it can be referenced as:

$url_list['some_id']['url']

and

$url_list['some_id']['time']

Here is the code:

$url_list[] = [ $eswc_id ][ 'url' => wp_get_referer(), 'time' => time() ];

It causes an error:

Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ']'

I'm new to PHP, I tried $eswc_id without the brackets and $url_list += instead of $url_list[] = but I'm getting the same error, how can I fix the syntax?

Ryszard Jędraszyk
  • 2,296
  • 4
  • 23
  • 52

1 Answers1

0

You can assign to that ID directly like this:

$url_list[$eswc_id] = [ 'url' => wp_get_referer(), 'time' => time() ];

The way you're doing it now,

  • [ $eswc_id ] creates a new array, and then
  • [ 'url' => wp_get_referer(), 'time' => time() ] tries to immediately dereference the array, but the arrow is not correct syntax to dereference.

That's kind of irrelevant since it's not what you're trying to do anyway, but that's why you're getting the error.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
  • I want to create a new ID with this piece of code. – Ryszard Jędraszyk Sep 05 '19 at 14:38
  • I thought `$eswc_id` was the a new ID that you had already created. I guess I misunderstood. So what is `$eswc_id` then? – Don't Panic Sep 05 '19 at 14:40
  • 1
    Maybe he wants `$url_list[] = array($eswc_id => array('url' => wp_get_referer(), 'time' => time()));` – Cid Sep 05 '19 at 14:43
  • @Cid thanks, I wanted exactly this! I used this structure a couple of months ago, but it escaped me! – Ryszard Jędraszyk Sep 05 '19 at 14:45
  • @Don'tPanic feel free to use my comment in your answer – Cid Sep 05 '19 at 14:46
  • 1
    @Ryszard With `$url_list[] = ...` you won't be able to access your entries as `$url_list['some_id']` though, it'll be `$url_list[0]['some_id']`… – deceze Sep 05 '19 at 14:47
  • 2
    @RyszardJędraszyk With that syntax, it is not possible to access the array the way you showed in the question. To get to url you would need `$url_list[an int]['some_id']['url']` rather than `$url_list['some_id']['url']`. – Don't Panic Sep 05 '19 at 14:47
  • Yep, that's either a badly asked question about the expected result or he's wrong about what I suggested – Cid Sep 05 '19 at 14:48