#1
  1. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Nobbies beach, Gold Coast. It's beautiful.
    Posts
    2,570
    Rep Power
    171

    Finding the last element of an array


    Is it the right way to find the last id of this array?[CODE]Array
    (
    [0] => Array
    (
    [id] => 121
    [code] => LBKW
    [class] => 1
    [category] => V
    [status] => 2
    [price] => 100.00
    [production_date] => 1971-08-10
    [STATUS] => in-active
    )

    [1] => Array
    (
    [id] => 400
    [code] => GSNC
    [class] => 5
    [category] => V
    [status] => 2
    [price] => 100.00
    [production_date] => 1980-08-08
    [STATUS] => in-active
    )

    [2] => Array
    (
    [id] => 520
    Code:
     => ORKT
                [class] => 7
                [category] => W
                [status] => 3
                [price] => 100.00
                [production_date] => 1967-10-22
                [STATUS] => pending
            )...
    PHP Code:
    function getLastId(&$array){
        
    $tmp=end($array);
        return 
    $tmp['id'];
    }

    echo 
    getLastId($data['results']); 
  2. #2
  3. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,692
    Rep Power
    6351
    This is going to move the array pointer, but if that doesn't matter to you then yes this is correct.

    You also should know that this doesn't guarantee the HIGHEST ID, unless this array was previously sorted by ID.
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.
  4. #3
  5. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,911
    Rep Power
    1045
    Hi,

    you do realize this will move the pointer of the original array to the end, changing it permanently? That's counterintuitive and can lead to a lot of confusion. Functions that are supposed to get or calculate something should have no side effects. I mean, when I call a function like getLastId(), I expect it to do exactly that and nothing else: get me the last ID. I don't expect it to change the array in any way.

    So either remove the passing by reference, or reset the pointer at the end of the function.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2009
    Posts
    667
    Rep Power
    6
    Are you aiming to get the data contained in the end of the array? Or the ID that's holding the data? If meerly the data, you can do something like:
    $final = count($array) - 1;
    $data = $array[$final];
  8. #5
  9. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,692
    Rep Power
    6351
    That only works if the indexes of this array are fully contiguous and haven't been disorganized, unsorted, or sourced from something else (like a SQL query)
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.
  10. #6
  11. Mad Scientist
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Oct 2007
    Location
    North Yorkshire, UK
    Posts
    3,660
    Rep Power
    4123
    maybe a bit too much memory use, but

    PHP Code:
    function getLastId($array){    //deliberately not passed by reference
        
    $tmp=array_pop($array); 
        return 
    $tmp['id']; 


    or


    PHP Code:
    function getLastId(&$array){
        
    $tmp=array_pop($array); //pop it off
        
    array_push($array,$tmp); //push it back on again - although the docs say to do $array[] = $tmp; instead....maybe need to test to see if $array is still an array as well
        
    return $tmp['id']; //use it

    I said I didn't like ORM!!! <?php $this->model->update($this->request->resources[0])->set($this->request->getData())->getData('count'); ?>

    PDO vs mysql_* functions: Find a Migration Guide Here

    [ Xeneco - T'interweb Development ] - [ Are you a Help Vampire? ] - [ Read The manual! ] - [ W3 methods - GET, POST, etc ] - [ Web Design Hell ]
  12. #7
  13. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,911
    Rep Power
    1045
    @ Northie: Did you find reset($array) too trivial?
  14. #8
  15. Mad Scientist
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Oct 2007
    Location
    North Yorkshire, UK
    Posts
    3,660
    Rep Power
    4123
    Originally Posted by Jacques1
    @ Northie: Did you find reset($array) too trivial?
    Never heard of it before....

    [goes to look it up, along with end()]

    ....In 10 years of coding PHP I have never needed to manually manage the array pointer....and don't intend to start
    I said I didn't like ORM!!! <?php $this->model->update($this->request->resources[0])->set($this->request->getData())->getData('count'); ?>

    PDO vs mysql_* functions: Find a Migration Guide Here

    [ Xeneco - T'interweb Development ] - [ Are you a Help Vampire? ] - [ Read The manual! ] - [ W3 methods - GET, POST, etc ] - [ Web Design Hell ]
  16. #9
  17. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Nobbies beach, Gold Coast. It's beautiful.
    Posts
    2,570
    Rep Power
    171
    I am pretty sure I am gonna get critics on this, but it does the job for me. Works fast and hasn't failed since. Comments are most welcome.
    PHP Code:
    class Results extends CI_Controller {
        
        public function 
    __construct()
           {
                
    parent::__construct();
                
    $this->price_type='';
                
    $data = array('title'=>'Mysql Php MVC''header'=>'Search for a product');
                
    $this->load->model('model_products');
                
    $this->load->view('header');
            }
        public function 
    show($link=NULL$record_starts=0)
            {
                if(
    $link=='prev')
                    {
                        
    $data['results'] = array_reverse($this->model_products->results_products_prev($this->session->userdata('search_data'), $record_starts));    
                    }
                if(
    $link=='next' || $link==NULL)
                    {
                        
    $data['results'] = $this->model_products->results_products($this->session->userdata('search_data'), $record_starts);    
                    }
                
                if(
    $this->next_link($data['results'], 'show'))
                    {
                        
    $data['next'] = $this->next_link($data['results'], 'show');    
                    }
                else
                    {
                        
    $data['next'] = "";    
                    }
                
                if(
    $record_starts!=0)
                    {
                        
    $data['prev'] = $this->previous_link($data['results'], 'show');    
                    }
                else
                    {
                        
    $data['prev']='';    
                    }
                
    $this->load->view('results',$data);
                
    $this->output->enable_profiler(TRUE);    
            }
                
        public function 
    price_range($record_starts=0)
            {
                
    $data = array('title'=>'Mysql Php MVC''header'=>'Search for a product');
                
    $this->load->model('model_products');
                if(
    $link=='prev')
                    {
                        
    $data['results'] = array_reverse($this->model_products->results_products_price_range_prev($this->session->userdata('search_data'), $record_starts));    
                    }
                if(
    $link=='next' || $link==NULL)
                    {
                        
    $data['results'] = $this->model_products->results_products_price_range($this->session->userdata('search_data'), $record_starts);
                    }
                
                if(
    $this->next_link($data['results'], 'price_range'))
                    {
                        
    $data['next'] = $this->next_link($data['results'], 'price_range');    
                    }
                else
                    {
                        
    $data['next'] = "";    
                    }
                if(
    $record_starts!=0)
                    {
                        
    $data['prev'] = $this->previous_link($data['results'], 'price_range');    
                    }
                else
                    {
                        
    $data['prev']='';    
                    }    
                
    $this->load->view('results',$data);
                
    $this->output->enable_profiler(TRUE);    
            }
        protected function 
    next_link(&$array$source)
            {
                
    $tmp=end($array);
                return 
    "<a class = \"yellow\" href=\"".base_url('results/'.$source.'/next/'.$tmp['id'])."\">Next Page >></a>";
            }
        protected function 
    previous_link(&$array$source)
            {
                
    $tmp=reset($array);
                return 
    "<a class = \"yellow\" href=\"".base_url('results/'.$source.'/prev/'.$tmp['id'])."\"><< Previous Page</a>";
            }    

    Model (parts of it)
    PHP Code:
    public function results_products($data$record_start=0,$number_of_records=50)
        {
            
    $this->db->select('products_table.id, code, class, category, status, price, production_date, products_status.title AS STATUS');
            
    $this->db->from('products_table USE INDEX (PRIMARY)');
            
    $this->db->join('products_status''products_status.id = products_table.status');
            
    $this->db->order_by('products_table.id');
            
    $this->db->where('products_table.id >'$record_start);
            
    $this->db->where($data);
            
    $this->db->limit($number_of_records);
            
    $query $this->db->get();
            return 
    $query->result_array(); 
        } 
  18. #10
  19. No Profile Picture
    Contributing User
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Dec 2004
    Posts
    2,868
    Rep Power
    368
    I apologies for derailing the thread but it seems you use CI and are pretty good at it.
    My q: in the model, do you not think it is easier to write a SQL query then to do this:

    Code:
    $this->db->select('products_table.id, code, class, category, status, price, production_date, products_status.title AS STATUS');
            $this->db->from('products_table USE INDEX (PRIMARY)');
            $this->db->join('products_status', 'products_status.id = products_table.status');
            $this->db->order_by('products_table.id');
            $this->db->where('products_table.id >', $record_start);
    I know people might do it because of easier portability to another DBMS (i.e. from Mysql -> Oracle) but in real life, who has done that? But I would be interested to hear your reasons as at the moment I just write plain queries instead of doing this?
  20. #11
  21. Mad Scientist
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Oct 2007
    Location
    North Yorkshire, UK
    Posts
    3,660
    Rep Power
    4123
    I second what paulh1983 says. I see this as a limitation of the framework, because by writing the actual SQL statement you can put in the order by, limit and offset based on the request variables. It may be the case that CI can do that and you just haven't figured out how yet. Somewhere on Devshed someone did post a good tutorial about pagination...E-Oreo maybe?
    I said I didn't like ORM!!! <?php $this->model->update($this->request->resources[0])->set($this->request->getData())->getData('count'); ?>

    PDO vs mysql_* functions: Find a Migration Guide Here

    [ Xeneco - T'interweb Development ] - [ Are you a Help Vampire? ] - [ Read The manual! ] - [ W3 methods - GET, POST, etc ] - [ Web Design Hell ]
  22. #12
  23. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Nobbies beach, Gold Coast. It's beautiful.
    Posts
    2,570
    Rep Power
    171
    Hi,
    For simple SQL queries I use Active Records but most of the times I write queries directly.

    E-Ore's pagination tutorial is a great idea, I think we should tell him
  24. #13
  25. No Profile Picture
    Contributing User
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Dec 2004
    Posts
    2,868
    Rep Power
    368
    another question, writing your queries directly, does CI automatically escapes the SQL params?
  26. #14
  27. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Nobbies beach, Gold Coast. It's beautiful.
    Posts
    2,570
    Rep Power
    171
    Originally Posted by paulh1983
    another question, writing your queries directly, does CI automatically escapes the SQL params?
    You can Bind
    PHP Code:
    $sql "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";

    $this->db->query($sql, array(3'live''Rick')); 
    Or
    PHP Code:
    $sql "INSERT INTO table (title) VALUES(".$this->db->escape($title).")"
    More examples

    Comments on this post

    • paulh1983 agrees : thanks. was just wondering if CI does it automatically like when you use the Active record
  28. #15
  29. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Nobbies beach, Gold Coast. It's beautiful.
    Posts
    2,570
    Rep Power
    171

    Lightbulb


    Hi. Yes active records automatically escape too. Very cool, bonus, excellent.

IMN logo majestic logo threadwatch logo seochat tools logo