0
  for ($i = 0; $i < count($keyListArray); $i++) {
      $newArray[$i] = $myArray[$keyListArray[$i]];
  }

//structure of arrays are as follows  
//$keyListArray = array (1,4,5);  
//$myArray = array(1=>array('hello', 4, 56, 7))
3
  • 1
    $myArray($keyListArray[$i]) is $myArray a callback function ? Commented Nov 5, 2010 at 13:14
  • 1
    If $myArray is an array, then it looks like you have a syntax error in your example. It should be $myArray[$keyListArray[$i]] Commented Nov 5, 2010 at 13:25
  • Thanks, I'm really sorry about that. Commented Nov 5, 2010 at 13:26

2 Answers 2

4

You're just trying to de-key $keyListArray, right? Try

$newArray = array_values($keyListArray);

array_values() returns all the values from the input array and indexes numerically the array. https://www.php.net/manual/en/function.array-values.php

-- Edit for new info

You have some parenthesis mixed up with square brackets - that's what has confused everyone. You don't really need the $i to specify the keys since they will be consistent and numerical by default. The way you're doing it is fine, but a foreach will make things a bit shorter.

foreach ($keyListArray as $key) {
  $newArray[] = $myArray[$key];
}
Sign up to request clarification or add additional context in comments.

2 Comments

no I dont think I'm trying to do that, I'm just trying to get a sub array of the existing array, using the specific keys of interest in $keyListArray But thank you!
You have parentheses where you need square brackets to access that existing array. Please see my changes.
3
 foreach($keyList as $key)
    $newArray[] = $myArray[$key];

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.