Loop error foreach: syntax error, unexpected 'foreach' (T_FOREACH), expecting ')' [closed]

-4

Can anyone tell me what I did wrong in this function? I can not find the error.

public function inserir_fotos() {

    $fotos = $this->input->post('fotos');
    $data = array(

    foreach ( $fotos as $item => $value){
        array(
            'idImovel' => $this->input->post('idImovel'),
            'imgImovel' => $value
        ),
    }
    );

        return $this->db->insert_batch('fotos', $data);

}
    
asked by anonymous 03.08.2015 / 21:17

2 answers

1

You can not use a loopback within a variable declaration. The right thing is you create the variable and go changing its value, in this case adding items in array .

Try to do as below:

public function inserir_fotos() {

    $fotos = $this->input->post('fotos');
    $data = array();

    foreach ( $fotos as $item => $value){
        array_push($data, array(
            'idImovel' => $this->input->post('idImovel'),
            'imgImovel' => $value
        ));
    }

    return $this->db->insert_batch('fotos', $data);

}
    
03.08.2015 / 21:22
4

You can not put foreach , for , while within an array directly, as far as I know, I've never seen any programming language that would allow / support such thing.

In php you should use this:

$data = array('a', 'b');
$data[] = 'foo';

print_r($data);//output: array('a', 'b', 'foo');

The code should be:

public function inserir_fotos() {

    $fotos = $this->input->post('fotos');
    $data = array();

    foreach ( $fotos as $item => $value){
        $data[] = array(
            'idImovel' => $this->input->post('idImovel'),
            'imgImovel' => $value
        );
    }

    return $this->db->insert_batch('fotos', $data);

}
    
03.08.2015 / 21:23