0

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

foreach($number_array as $number)
{                 
  if(strlen($number)==10)
  {      
    //How to insert the number values into an array ??                  
  }
}
1
  • This is kind of basic. Is it a part of a homework assignment? Commented Sep 27, 2011 at 13:29

3 Answers 3

2
$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 ;)

Sign up to request clarification or add additional context in comments.

Comments

1

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;
});

Comments

1

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);
  }
}

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.