简体   繁体   中英

How to get N element values of an array not based on the key but on array element order

I have an array looking like this:

552="text"
75="text"
120="text"
1254="text"
187="text"
...

I want to use array_slice() on it to get the first 3 element values and implode them but since the keys are random, array_slice() doesn't seem to work with this because i don't know the keys.

            $list_sliced = array_slice($list, $slice_from, $slice_to);
            $u_array[] = implode(',', $list_sliced);

How can i get the first 3 element values of an array with random keys?

EDIT: I actually found a solution by using this before I slice my array $new_array = array_values($old_array);

I'f you used array_values to reset the keys , you can use array_splice as expected:

Small example:

<?php

$ar = [];
$ar[75] = 'Text 75';
$ar[552] = 'Text 552';
$ar[1254] = 'Text 1254';
$ar[1756] = 'Text 1756';

$ar = array_values($ar);

$sliced = array_slice($ar, 0, 3);
var_dump($sliced);
array(3) {
  [0]=>
  string(7) "Text 75"
  [1]=>
  string(8) "Text 552"
  [2]=>
  string(9) "Text 1254"
}

Try it online!

You can use array_chunk()

$output = array_chunk($input_array, 3);
var_dump($output[0]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM