1

I want to store all value in a array and get out from the loop is it possible?

<?php
    $a=array('a', 'b', 'c');
    foreach($a as $b)
    {
        for($i=0; $i<count($a); $i++)
        {
            $c = array();
            $c[$i] = $b;     
        }

        print_r($c);
    }
?>
3
  • 1
    Can't you just $c = $a; and print_r($c); ?? Commented Dec 9, 2013 at 17:47
  • What are you trying to do? Regarding your code you're expecting $c = array('a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c');? Commented Dec 9, 2013 at 17:49
  • What is your expected output ? Commented Dec 9, 2013 at 17:53

4 Answers 4

3

I made a mistake the array variable $c=array() should be out side of loop

<?php

   $a=array('a','b','c');

   $c=array();
   // for loop
   for($i=0;$i<count($a);$i++){
       $c[$i]=$a[$i];
   }
   // forEach loop
   foreach ($a as $b){
         $c[]=$b;
   }
   // while loop
   $x=0;
   while($x<count($a)){
          $c[$x]=$a[$x];
          $x++;
   }

  print_r($c);
?>
Sign up to request clarification or add additional context in comments.

Comments

1

Can you try this, Moved $c = array(); from inside forloop into outside the forloop.

<?php
   $a=array('a','b','c');
    foreach($a as $b){
        $c = array();
        for($i=0;$i<count($a);$i++){                
            $c[$i]=$b;
        }
        print_r($c);
    }
?>

1 Comment

no its wrong. in this i am getting $c[0]==123 and $c[1]==123. I dont want like this. I want $c[0]==1,$c[1]==2,$c[2]==3. Like this
0

Why you are defining array at each iteration?

<?php
$a=array('a','b','c');
foreach($a as $b){
    $c=array();
    for($i=0;$i<count($a);$i++){
    $c[$i]=$b;     
}
print_r($c);
}
?>

Comments

0

The best way to storing values in empty array using foreach.

$coll_courses = array();
foreach ($courses as $req_courses){
    $coll_courses[] = $req_courses;
}
echo "<pre>";
print_r($coll_courses);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.