2

I have the following array:

array (size=2)
  0 => 
    array (size=4)
      0 => string 'http://localhost/wp/wp-content/uploads/2013/03/slider-area.jpg' (length=62)
      1 => int 1584
      2 => int 346
      3 => boolean false
  1 => 
    array (size=4)
      0 => string 'http://localhost/wp/wp-content/uploads/2013/03/featured.jpg' (length=59)
      1 => int 1584
      2 => int 346
      3 => boolean false

My Question is that how can I loop through this array to generate a new array that contains only two values as following:

$result_array = array(
    0 => "http://localhost/wp/wp-content/uploads/2013/03/slider-area.jpg",
    1 => "http://localhost/wp/wp-content/uploads/2013/03/featured.jpg"
);

I have tried a foreach loop but could not get the required result array. I tried the following loop:

foreach ( $array as $key => $value ){
    foreach ( $value as $item){
        $result_array[] = $item;
    }
}
0

4 Answers 4

1

You were close:

$result_array = array(); //Initialization is important.

foreach ($array as $value) {
    $result_array[] = $value[0]; // $value[0] is the first element in the inner array.
}
Sign up to request clarification or add additional context in comments.

Comments

1

It should be as simple as this:

$finalArray = array();    
foreach($array as $arrayitem){
  $finalArray[] = $arrayItem[0];  
}

Comments

1

To do this with foreach:

foreach( $array as $key => $value ) {
    $result_array[$key] = $value[0];
}

(don't use a foreach inside a foreach unless you want to iterate through 2 dimensions!)

1 Comment

Looking at the other answers which use [], they will not always give you values in the same order. This method uses the old key in the new array, so they are guaranteed to match.
0

I'll just throw this pretty little one-liner in here for the fun of it :)

$newArray = array_map(function($a){ return $a[0]; }, $myArray);

run code

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.