tags:

views:

97

answers:

1

Hi,

In my cakePHP controller there is an action named saveReport() where $attribute_ids is an array holding all the selected attributes obtained from the Ajax post..

function saveReport()
{
    echo $this->params['form']['formid'];
    echo $this->params['form']['reportTitle'];
    echo $this->params['form']['attr'];
    $attribute_ids=$this->params['form']['attr'];
    $comma_separated = explode(",", $attribute_ids);

    for($i=0;$i<15;$i++)
    {
        echo $comma_separated[$i]; 
        echo "     ";

        $this->data['Report']['title']=$this->params['form']['reportTitle'];
        $this->data['Report']['form_id']=$this->params['form']['formid'];
        $this->data['Report']['attr_id']=$comma_separated[$i]; 
        $this->Report->saveAll($this->data);
    }
}

how to identify $comma_separated 's length where $comma_separated is an array so that i can use that in the for loop now i have used as 15 by default...

+3  A: 

Hi,

If $comma_separated is an array, you can use count to find out how many elements it contains.

For instance, if you array contains this :

$comma_separated[0] = 'glop';
$comma_separated[1] = 'hello';
$comma_separated[2] = 'world';

You can use :

$result = count($comma_separated);
var_dump($result);

And will get :

int 3


You could also use foreach to iterate over the elements of your array, instead of for ; this way, you won't need to know how many elements it contains.

For instance :

foreach ($comma_separated as $element) {
    var_dump($element);
}

Will get you :

string 'glop' (length=4)
string 'hello' (length=5)
string 'world' (length=5)
Pascal MARTIN
+1 for Pascal aka the PHP Man ;)
Learner