Welcome Guest, Not a member yet? Register   Sign In
Any way of doing this shorter? (splitting an array)
#1

[eluser]Bramme[/eluser]
Hey all

I'm working on a more advanced version of my first auth lib. I've got a method that looks like this:

Code:
function generate_user_fields()
    {
        $this->user_fields = $this->CI->db->list_fields($this->users_table);
        $this->no_access[] = $this->id_column;
        for ($i = 0; $i < count($this->user_fields); $i++)
        {
            if (in_array($this->user_fields[$i], $this->no_access)) {
                unset($this->user_fields[$i]);
            }
        }
    }
I wondered if there was no array function that would do this automatically for me... I've went through the php documentation (rather quickly) and the only function I saw that could come close is array_filter, which still needs a user made callback...


And a quick additional question: which function does the language library use again to replace the %s in strings with a value. I found it once but forgot Sad
#2

[eluser]BorisK[/eluser]
I think array_intersect is what you're looking for. Try this untested code:

Code:
$result = array_intersect($this->user_fields, $this->no_access);

foreach($result as $key=>$value) {
  unset($key);
}
#3

[eluser]Elliot Haughin[/eluser]
That looks pretty good BorsK...

And, another thing you might want to remember.
If ever you're doing a for loop, or a while loop, makes sure you don't use methods in the conditional statement, since they are executed on every iteration.

so:

Code:
for ($i = 0; $i < count($this->user_fields); $i++)

should be:

Code:
$max = count($this->user_fields);
for ($i = 0; $i < $max; $i++)

It's only a slight optimization, but they all add up!

Elliot
#4

[eluser]Armchair Samurai[/eluser]
[quote author="Bramme" date="1225645145"]
And a quick additional question: which function does the language library use again to replace the %s in strings with a value. I found it once but forgot Sad[/quote]
sprintf() or printf().
#5

[eluser]Bramme[/eluser]
thanks a bunch guys! I saw that intersect function, but didn't understand it too goody goody. And thanks for the hint Elliot, you're right, it might not matter if it only has to count an array with 5 keys ten times, but imagine what it would be if it were an array with 200 keys 2000 times... Things would start to add up :p




Theme © iAndrew 2016 - Forum software by © MyBB