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))
2 Answers
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];
}
2 Comments
Mohammad
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!Scott Saunders
You have parentheses where you need square brackets to access that existing array. Please see my changes.
$myArray($keyListArray[$i])is $myArray a callback function ?$myArrayis an array, then it looks like you have a syntax error in your example. It should be$myArray[$keyListArray[$i]]