1

In the array below, how can I push the new array into the $options array at the specified location?

$options = array (
    array( "name" => "My Options",
    "type" => "title"),
    array( "type" => "open"),

    array("name" => "Test",
    "desc" => "Test",
    "id" => $shortname."_theme",
    "type" => "selectTemplate",
    "options" => $mydir ),

//I want the pushed array inserted here.

    array("name" => "Test2",
    "desc" => "Test",
    "id" => "test2",
    "type" => "test",
    "options" => $mydir ),

    array( "type" => "close")
    );

    if(someCondition=="met")
    {
    array_push($options, array( "name" => "test",
        "desc" => "description goes here",
        "id" => "testMet",
        "type" => "checkbox",
        "std" => "true"));
    }

4 Answers 4

7

You can use array_splice. For your example:

if($some_condition == 'met') {
  // splice new option into array at position 3
  array_splice($options, 3, 0, array($new_option));
}

Note: array_splice expects the last parameter to be an array of new elements, so for your example you need to pass an array containing the new option's array.

Sign up to request clarification or add additional context in comments.

Comments

2

Simply

array_splice($options, 3, 0, $newArr);

Comments

1

for insert a new array, not to a spesific location(between $r[4] and $r[5]):

$options[]=array ("key" => "val"); //insert new array
$options[]=$v; //insert new variable

to insert a new array after spesific variable:

function array_push(&$array,$after_element_number,$new_var)
{
  array_splice($array, $after_element_number, 0, $new_var);
}

if(someCondition=="met")
{
array_push($options, 2, array( "name" => "test",
    "desc" => "description goes here",
    "id" => "testMet",
    "type" => "checkbox",
    "std" => "true"));
}

Comments

0

As connec says, you can use array_splice, but without forgetting to wrap your array in another array, like this:

if ('met' === $some_condition)
{
  array_splice($options, 3, 0, array(array(
    'name' => 'test',
    'desc' => 'description goes here',
    'id'   => 'testMet',
    'type' => 'checkbox',
    'std'  => 'true'
  )));
}

Edit: connec has already specified its response.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.