1

I have code that will make an array or arrays of UNKNOWN length because it depends on how many new people have been added to the mysql DB. (this is where I'm getting confused)

The array has $x items, each item is an array of first name, last name, and e-mail address.

I want the loop to run till the array is ended.

$x = 0;
while($array[$x]['per_LastName'] != 'NULL') {
    $batch[] = array('EMAIL'=>$array[$x]['per_Email'], 'FNAME'=>$array[$x]['per_FirstName'], 'LNAME'=>$array[$x]['per_LastName']);
    $x = $x+1;
    }

apparently I'm looping infinity because it uses all the memory.

2
  • 3
    Why not use a foreach here? foreach($array as $val){ $val['per_LastName'] } Commented Jun 19, 2013 at 19:38
  • For what it's worth, your loop is currently looping infinitely because you're comparing with 'NULL'. The single quotes mean that this is a string, which contains the word NULL, which is different from an actual NULL value. Commented Jun 19, 2013 at 19:41

3 Answers 3

3

Use a foreach loop which will loop through all elements of the array.

foreach($array as $key => $value) {
    $batch[] = array('EMAIL'=>$value['per_Email'], 'FNAME'=>$value['per_FirstName'], 'LNAME'=>$value['per_LastName']);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Works. Thanks. Can you elaborate on the way this works or link me something. I searched a lot but didn't see a way to do this.
A foreach loop goes through each element of the array $array and runs the loop for each one. The $key => $value means that they key of the array element will be stored in $key and its value in $value. See php.net/manual/en/control-structures.foreach.php for more information.
2

Instead you should use a for loop

for($x = 0; $x<count($array); $x++){
    $batch[] = array('EMAIL'=>$array[$x]['per_Email'], 'FNAME'=>$array[$x]['per_FirstName'], 'LNAME'=>$array[$x]['per_LastName']);
}

Comments

2

why not use foreach and avoid counters and unnecessary checks?

foreach($array as $eachArray)
{
    $batch[] = array('EMAIL'=>$eachArray['per_Email'], 'FNAME'=>$eachArray['per_FirstName'], 'LNAME'=>$eachArray['per_LastName']);
    }

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.