0

In C++ and JavaScript it was recommended to create an array with specified length, and then populate it. Is there a syntax to do so in PHP? Or there's no need because PHP's array is a hash?

ps: I'm populating an array from mysql using mysql_fetch_array and I'm running a loop to it so =(

3 Answers 3

2

You can use SplFixedArray from the Standard PHP Library (SPL), if performance is really important. In general reguluar php arrays will be fine, without worrying about the size of array required.

http://www.php.net/manual/en/class.splfixedarray.php

They work like arrays do in other langauges. From the docs "The advantage is that it allows a faster array implementation."

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

1 Comment

Thanks, I've never heard about SplFixedArray! I'll test the performance later to choose the best way
1

You can do something like that:

$size = 10;
$data = new SplFixedArray($size);
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
    if($data->offsetExists($i)) {
        $data[$i] = $row;
    } else {
        $size += 10;
        $data->setSize($size);
        $data[$i] = $row;
    }
    $i++;
}

But my advice is stick to normal arrays.

2 Comments

but I can use mysql_num_rows to find the exact size of the SplFixedArray. I think that's just what I need!
I hope I can fully use SplFixedArray as normal array without rewriting a single line of code in other places...
1

You don't have to worry at all.
Despite of theoretical recommendations from some ancient book, in the real life practical usage the difference would be negligible and you'll never notice the difference.

Usual web-page seldom being populated with more than 100 rows from the database. Trust me, an array of such size is not a thing to worry about.
If it happen to have an array of much bigger size, you have to consider not to use arrays at all first.

1 Comment

but if we have to populate 100 rows, then SplFixedArray is 30%(!) faster than a standard array! ;P

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.