0

I have an array ($skus), which looks like this;

$skus[0] = "hello";
$skus[1] = "world";
$skus[2] = "sky";
$skus[3] = "is";
$skus[4] = "blue";

My question is, how can I get a subset of this array based on another array, i.e. the subset array is;

$words = array(0,2,4);

which will return to me an array with ["hello", "sky", "blue"], i.e.

$return[0] = "hello";
$return[1] = "sky";
$return[2] = "blue";
1
  • did u tried the solutions??? Commented Aug 15, 2019 at 15:32

2 Answers 2

0

You might use a for loop and check if the index from $words exists in $skus:

$skus = [

    "Hello",
    "world",
    "sky",
    "is",
    "blue",
];

$words = array(0,2,4);
$result = [];
for ($i = 0; $i < count($words); $i++) {
    if (isset($skus[$words[$i]])) {
        $result[$i] = $skus[$words[$i]];
    }
}

print_r($result);

Result

Array
(
    [0] => Hello
    [1] => sky
    [2] => blue
)

Php demo

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

Comments

0

You can use array_intersect_key() with array_flip():

<?
$skus[0] = "hello";
$skus[1] = "world";
$skus[2] = "sky";
$skus[3] = "is";
$skus[4] = "blue";

$words = array(0,2,4);

$result = array_intersect_key($skus, array_flip($words)); 
$setOrder = array_values($result); // to re order
echo "<pre>";
print_r($setOrder);
?>

Result:

Array
(
    [0] => hello
    [1] => sky
    [2] => blue
)

You can also use array_values() to reset the key order.

DEMO

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.