1
$region_array = array( 

                                1 => 'Region 01', 
                                2 => 'Region 02',
                                3 => 'Region 03'
        );

What I'm trying is

array_slice($region_array, $index); & array_splice($region_array, $index); both does not give me required output.

Required output is

  1. if the pass 2 as the index only 1st two element should be left. if I pass 3 1st three element should be left. How can I do it?

  2. Then whatever the output array is I want to add 0 => 'Select Region' as the 1st option of the output array. I tried array_push. It adds the element to the end of the array. How can I fix it?

1

4 Answers 4

4

To answer point #2 first, use array_unshift -> https://www.php.net/manual/en/function.array-unshift.php

To point #1, use array_slice($region_array, 0, $index);

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

Comments

3
`<?php 
    $region_array = array( 
        1 => 'Region 01', 
        2 => 'Region 02',
        3 => 'Region 03'
    );
    $array = array_slice($region_array, 0, 2);
    array_unshift($array, 'Select Region');
    echo '<pre>';
    print_r($array);
 ?>`

Comments

1
$array = array_slice($region_array, 0, $index)
array_unshift($array, 'Select Region');

read the documentation for array_slice and array_unshift

1 Comment

you don't need to use array('0' => 'Select Region'), in fact, I think that will push an array on to the front and make it two-dimensional. just need array_unshift($array, 'Select Region');
1

Since your array indices are greater than zero you can use this one-liner as well:

$result = array('Select region') + array_slice($region_array, 0, $index, true);

The + operator works on arrays and concatenates the second array (only the items whose key doesn't intersect with the first).

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.