开发者

PHP: How to insert element into an array from variable

I need to insert valus into a array.How i do that. my code is below:

foreach($number_arra开发者_如何学运维y as $number)
{                 
  if(strlen($number)==10)
  {      
    //How to insert the number values into an array ??                  
  }
}


$new_array = array();

foreach($number_array as $number)
{                 
  if(strlen($number)==10)
  {      
    $new_array[] = (int) $number;                
  }
}

This adds all numbers of the number_array that are of length 10 to the new_array ;)


Though both answers are correct; it seems to me that the foreach is useless, you can achieve this just as well with array_filter, which is faster and easier to use (from my point of view, anyway):

<?php
$newArray = array_filter( $number_array, function( $element ) {
   return strlen( $element ) === 10;
});


Append them onto $array with the [] notation, or use array_push().

// Start with empty array.
$array = array();
foreach($number_array as $number)
{                 
  if(strlen($number)==10)
  {      
    // Append $number to $array                 
    $array[] = $number;

    // Alternatively, use array_push()
    array_push($array, $number);
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜