0

I have this array structure, it is stored in a variable $xxx

Array
(
    [xyz] => Array
        (
            [1] => 3
            [0] => s
        )

    [d2s] => Array
        (
            [a] => 96
            [d] => 4

         )
...
)

It is a long array, and I don't want to out put the whole thing, how do print only the first 5 (1st dimension) values along with the 2nd dimension values?

Secondly, if I want this array to contain only alphabets in the FIRST dimension, how do I either delete values that don't match that requirement or retain values that match the requirement? so that my final array would be

Array
(
    [xyz] => Array
        (
            [1] => 3
            [0] => s
        )

...
)

TIA

2
  • @josh, I tried foreach ($main as $val), and then match pattern against $val, if no match, unset($main[$val]), but I get the error saying that expected $val as a string but it is an array. Commented Mar 17, 2012 at 2:06
  • I offered a solution, but it would be best to provide the code you're having trouble with along with the error. Commented Mar 17, 2012 at 2:19

1 Answer 1

1

To output only the first 5 elements, use array_slice:

array_slice($arr, 0, 5)

To remove any elements whose index contains non-alpha characters.

foreach ($arr AS $index => $value) {
        // Remove the element if the index contains non-alpha characters
        if (preg_match('/[^A-Za-z]/', $index))
                unset($arr[$index]);
}

Check it out in action.

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

3 Comments

Hi Josh, thanks for the code, I actually did the 2nd part of the code exactly the same way you just did and it works. As for the first part, I meant to say print out the 1st dimension value and the 2nd dimension values (I left out the 'dimension' in my original question, sorry). I was basically looking for a quick way of using print_r, something like print_r ($arr,0,5), but I guest that function does not exist. Thanks again.
That makes more sense. A native function does exist for what you're looking for. I've updated the solution accordingly.
haha, array slice, doh! moment for me, and to think I have been using print_r and waiting like a fool for the output to print all these times.

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.