Search code examples
arrayskeyprefix

How to access an array element whose key starts with some unique string in PHP?


From the following array:

area = Array
    (
        sur12 => 2
        abb12 => 5
        sur13 => 6
        abb13 => 4
        sur14 => 8
        abb14 => 4
        sur15 => 2
        abb15 => 5
        abb16 => 8
        abb17 => 5
        abb18 => 4
        abb19 => 2
        abb20 => 6
        abb21 => 9
        abb22 => 5
        abb23 => 9
        abb24 => 8
        sur_count15 => 4
        abb_count24 => 2
    )

how do I access area['sur_count15'] if I only know the prefix sur_count, or area['abb_count24'] if I only know the prefix abb_count?

Is there any way to do this in PHP, like, e.g. in CSS where I can access an ID that starts with abc_count by using [id*="abc_count"]?

The prefix is unique to the first 3 characters.


Solution

  • I ended up using the answer to my other question over at How to get a subset of $_POST array with keys starting with a prefix. If only I could restructure the array, but that's a no-go for now. Thanks, y'all.