0

I am new to PHP an needed little help. It may be easy for some but giving me a tough time.

I have an array

Array ( [0] => page-18 [1] => page-20 )

Which I would like to explode further by '-':

$mainStringBrk = array('page-18', 'page-20');
$finalArray = array();
foreach($mainStringBrk as $bString){
    $mainStringBrkBrk = explode('-', $bString);
    $finalArray[$mainStringBrkBrk[0]] = $mainStringBrkBrk[1];
}
echo '<pre>'; print_r($finalArray);

When I do, it outputs only the last key and value of array.

Array ( page => 20 )

My desired output is:

Array ( page => 18, page => 20 )

I am wondering if anyone can guide me in right direction.

1
  • 1
    The problem is that you can't have 2 keys the same in an associative array, so the second one is overwriting the first. Commented Dec 1, 2019 at 20:35

1 Answer 1

1

You can't achieve the result you want as it is not possible to have an array with identical keys; this is why you only have one result in your output. You could change your output structure to a 2-dimensional array to work around this e.g.

$mainStringBrk = array('page-18', 'page-20');
$finalArray = array();
foreach($mainStringBrk as $bString){
    $mainStringBrkBrk = explode('-', $bString);
    $finalArray[$mainStringBrkBrk[0]][] = $mainStringBrkBrk[1];
}
print_r($finalArray);

Output:

Array
(
    [page] => Array
        (
            [0] => 18
            [1] => 20
        )
)

Or you can adopt this structure if it is better suited to your needs:

$finalArray = array();
foreach($mainStringBrk as $bString){
    $mainStringBrkBrk = explode('-', $bString);
    $finalArray[] = array($mainStringBrkBrk[0] => $mainStringBrkBrk[1]);
}
print_r($finalArray);

Output:

Array
(
    [0] => Array
        (
            [page] => 18
        )
    [1] => Array
        (
            [page] => 20
        )
)

Demo on 3v4l.org

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

4 Comments

Thanks, but how can I achieve Array( [page] => 18 [page] => 20 )?
As I explained at the beginning of my answer, and as @NigelRen said in his comment to your question, that is not possible as it would require an array to have identical keys. If that was allowed what result would you expect to get from $array['page']? 18? or 20?
Thanks for the guidance. I think I will stick to $finalArray[] = array($mainStringBrkBrk[0] => $mainStringBrkBrk[1]); in that case.
@DevChauhan no worries - what you propose is another valid way of splitting the data. For completeness I'll add it to the answer.

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.