 <p>Same as @hsz answer but with one difference..</p> <pre><code>foreach ($test as $key=&gt;$value) { // +1 because 1st array key is 0 ${'test' . ($key+1)} = $value; } </code></pre> <p>or with counter</p> <pre><code>$i = 1; foreach ($test as $value) { ${'test' . $i++} = $value; } </code></pre> <p>But it all depends on what you really need.. Once you have your values in 1 array you can use them a lot easier then creating such variables..</p> <p>.. For the SQL please check my edit</p> <pre><code>function rapport_detail_kosten($idKlant){ $this-&gt;db-&gt;from('Project'); $this-&gt;db-&gt;join('Kosten', 'Kosten.idProject = Project.idProject'); if ($idKlant &gt; 0){ $this-&gt;db-&gt;where('idKlant', $idKlant); } $query = $this-&gt;db-&gt;get(); $project = array(); foreach($query-&gt;result() as $row){ $project[] = $row-&gt;idProject; } $sum = 0; $this-&gt;db-&gt;select('Kosten.idProject, SUM(Kosten.idProject) as sum'); $this-&gt;db-&gt;from('Kosten'); $this-&gt;db-&gt;where_in('Kosten.idProject',$project); $query = $this-&gt;db-&gt;get(); if($query-&gt;num_rows()&gt;0){ return $query-&gt;result(); } return false; } </code></pre>