1

I have this array:

Array ( 
[0] => Array ( [0] => b [1] => d [2] => c [3] =>a [4] => ) 

[1] => Array ( [0] => c [1] => a [2] => d [3] => [4] => ) 

[2] => Array ( [0] => b [1] => d [2] => a [3] => [4] => )

[3] => Array ( [0] => a [1] => d [2] => c [3] =>b [4] => )

)

and was wondering whether I can copy all inner array from it to another array where the first element is "b" so it looks like. Will the new array be reindexed when created? Thank you.

Array ( 
[0] => Array ( [0] => b [1] => d [2] => c [3] =>a [4] => ) 

[1] => Array ( [0] => b [1] => d [2] => a [3] => [4] => )

)

2 Answers 2

3

UPDATE: Had a little error in my code. Now it is fixed and working if you still need it.

$firstArray = array (array ('b', 'd', 'c', 'a'), 
                     array ('c', 'd', 'a', 'b'), 
                     array ('b', 'd', 'a', 'c'), 
                     array ('a', 'd', 'c', 'b'));

$secondArray = array();

foreach($firstArray as $sub) {

    if($sub[0] == 'b') {

        $secondArray[] = $sub;
    }
}

print_r($secondArray);

Output:

Array ( [0] => Array ( [0] => b [1] => d [2] => c [3] => a ) 
        [1] => Array ( [0] => b [1] => d [2] => a [3] => c ) )
Sign up to request clarification or add additional context in comments.

1 Comment

I was using: foreach($firstArray as $sub=>$value) and was checking for $value[0] instead of $sub[0], as well as $secondArray[] = $sub[0]; and was saving just the first element! $sub is really the full array! Doh! Appreciate it!
2
function check($val) {
     return ($val[0] == 'b');
}
$secondArray = array_filter($firstArray, "check");

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.