Search code examples
phparraysiterator

If next item in looping array exists


I want to check to see if within the current position of an array loop there is a further 1 or more elements left (without shifting the elements and counting):

public function build() {
    $_string = 'CREATE TABLE IF NOT EXISTS `' . dbbuilder::$prefix . $this->name . '` (';
    foreach( $this->rows as $key => $row ) {
        if( $__string = $row->get_string() ) {
            $_string .= $__string . ( next( $this->rows[$key] ) ? ', ' : '' );
        }
    }
    $_string .= ') ENGINE=InnoDB  DEFAULT CHARSET=utf8;';
    $this->string = $_string;
}

Output:

[string:private] => CREATE TABLE IF NOT EXISTS `ecom_accounts` (`id` init(11) NOT NULL  AUTO_INCREMENT`name` varchar(55) NOT NULL `email_address` varchar(255) NOT NULL `password` varchar(32) NOT NULL `multisite` varchar(5) NOT NULL `roll` int(4) NOT NULL DEFAULT '0') ENGINE=InnoDB  DEFAULT CHARSET=utf8;

I thought next() would work but it doesnt, also the key is a string not number.


Solution

  • What about the easy one?

    $_string = 'CREATE TABLE IF NOT EXISTS `' . dbbuilder::$prefix . $this->name . '` (';
    $tmp=array();
    foreach( $this->rows as $key => $row )
       if( $__string = $row->get_string() )
          $tmp[]=$__string;
    $_string .= implode(',',$tmp);
    $_string .= ') ENGINE=InnoDB  DEFAULT CHARSET=utf8;';
    $this->string = $_string;