3

I have this kind of simple array:

$puctures=array('1_noname.jpg','2_new.jpg','1_ok.jpg','3_lets.jpg','1_stack.jpg','1_predlog.jpg','3_loli.jpg');

I want to make new array that i will only have elements thats starts with 1_ Example

$new=array('1_noname.jpg','1_ok.jpg','1_stack.jpg','1_predlog.jpg');

Something like array_pop but how?

Miomir Dancevic
  • 6,726
  • 15
  • 74
  • 142

5 Answers5

4

See array_filter():

$new = array_filter(
    $puctures,
    function($a) {return substr($a, 0, 2) == '1_'; }
);
Oswald
  • 31,254
  • 3
  • 43
  • 68
3

Use array_filter() to get your array:

$new = array_filter($puctures, function($item)
{
   //here strpos() may be a better option:
   return preg_match('/^1_/', $item);
});
Alma Do
  • 37,009
  • 9
  • 76
  • 105
  • 2
    `preg_match` is better. The compiled regex is cached. `strpos` walks through the whole `$item` before determining that the found position is != 0. – Oswald Oct 11 '13 at 08:58
3

A simple loop will do.

foreach ($pictures as $picture) {
    if (substr($picture, 0, 2) == "1_") {
        $new[] = $picture;
    }
}
Ian Brindley
  • 2,197
  • 1
  • 19
  • 28
2

This examples uses array_push() & strpos()

$FirstPictures = array();
foreach( $pictures as $pic => $value ) { 
   if ( strpos( $value, '1_' ) !== 0 ) {
      array_push( $FirstPictures, $pic );
   }
}
MackieeE
  • 11,751
  • 4
  • 39
  • 56
0
$puctures=array('1_noname.jpg','2_new.jpg','1_ok.jpg','3_lets.jpg','1_stack.jpg','1_predlog.jpg','3_loli.jpg');
  $new=array();
  foreach($puctures as $value)
   {
   if(strchr($value,'1'))
   $new[]=$value;
   }
   echo "<pre>";  print_r($new); 
senthil
  • 324
  • 2
  • 15