Search code examples
phphtmlarraysarray-push

array_push() throws an error


This is my array:

Array (
[country_0] => E92000001
[country_1] => L93000001
[country_2] => M83000003
[county_0] => E10000002
[county_1] => E10000003
[county_2] => E10000006
[county_3] => E10000007
[gor_0] => A
[gor_1] => B
)

I would like to get something like this:

Array
(
[country] => Array(
              [0] => L93000001
              [1] => M83000003
              [2] => M83000003
             )

[county] => Array(
              [0] => E10000002
              [1] => E10000003
              [2] => E10000006
              [3] => E10000007
             )
[gor] => Array(
              [0] => A
              [1] => B
             )
)

My code for doing this is currently this:

$converted_array = [];

    foreach ($input as $key => $value) {

        $underscore_position = strpos($key, "_"); //returns integer.

        $stripped_key = substr($key, 0, $underscore_position); //returns word eg "country"

        array_push($converted_array[$stripped_key], $value); //doesn't work
        array_push($converted_array, $stripped_key[$value]); //doesn't work
        array_push($converted_array, $stripped_key => $value); //doesn't work
    }

    print_r($converted_array);

I can't get any of my array_push()s to work. I keep getting a syntax error or illegal offset error.

Perhaps this is not the best way. I am basically trying to manipulate hidden form post data. Each hidden field will look something like this:

<input name="country_0" type="hidden" value="E92000001">

The number after the country_ is only to keep each input unique. So maybe it would be better to have something like <input name="country_E92000001" type="hidden" value="E92000001"> and do some sort of array key splicing.

So how can I get my code to work or is there a better way?

EDIT:

To generate the hidden input fields I use this code:

<input name="<?php echo $key; ?>" type="hidden" value="<?php echo $subvalue; ?>">

As a result, adding [] gives me a Cannot use [] for reading error. Is there any way to solve this?


Solution

  • Just change the name attribute of your input field to this:

    <input name="country[]" type="hidden" value="E92000001">
                      //^^
    

    Then it will automatically be an array.

    EDIT:

    As from your updated code you can use the code below to add [] to the name:

    <input name="<?php echo strtok($key, "_") . "[]"; ?>" type="hidden" value="<?php echo $subvalue; ?>">