0

Let's say I have this array :

$cars = array("Saab","Volvo","BMW","Toyota");

and I also have this Foreach loop to 'manipulate' that array :

foreach ($cars as $carsdata) 
    { 
        if (*this is array[0]) {
            do something here
        }else if (*array[1] ... array[x]){
            do another thing here
        }        
    }

any idea how to write that Foreach correctly? thanks.

6 Answers 6

8

You could include a simple boolean like this:

$firstRow=true;
foreach ($cars as $carsdata) 
{ 
    if ($firstRow) 
    {
        $firstRow=false;
        // do something here
    }
    else
    {
        // do another thing here
    }        
}
Sign up to request clarification or add additional context in comments.

2 Comments

+1... best solution if array has valued keys, or unsorted numbers.
@glavić Don't sell yourself short, your answer is excellent based on the question as it stands :)
7

In your case your array is number-indexed, so actually you can do this:

foreach ($cars as $index => $carsdata) 
{ 
    if ($index == 0) { // array[0]
        do something here
    } else { // *array[1] ... array[x]
        do another thing here
    }        
}

1 Comment

Beaten to it, it seems. exposing the index will solve most foreach-related problems
5

If you have indexed array $cars like your entered in question, then this will work :

foreach ($cars as $i => $carsdata) {
    if (!$i) {
        // do something with first
    } else {
        // do something with second+
    }
}

Comments

2

Would this work?

foreach ($cars as $key => $carsdata) {
     if ($key == 0) {
        //do
    } else {
        //do
    }
}

Comments

1

Another possibility

$i = 0;
$len = count($carsdata);
foreach ($cars as $carsdata) 
{ 
    if ( $i == 0 ) {
        // first element
        // do something here
    }else if ($i == $len - 1){
        // last element
        // do another thing here
    } else {
        // do the rest here
    } 
    $i++;     
}

Comments

0
foreach ($cars as $carsdata=>value) 
{ 
    if($value==0){
        // Do the things for the o th index 
    }
    else{


    }
}

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.