Limit an array size

0

I have an array and will use it in two ways, in one I will use all elements of this array, and in the other I will limit to, for example, 2 elements, eg

$array = ('nome'=>'Ribossomo', 'snome'=> 'Silva', 'idade'=> 500);

using all elements:

$user = $array;

Now, how can I get only the first 2 elements of this array? for example, the elements nome and snome

$teste = ?
    
asked by anonymous 17.07.2016 / 16:37

2 answers

3

I think that if I understand it is very easy, you just get the array and put the position (index) you want. Example:

<?php
 $primeiro=$array[0]; //Ribossomo
$segundo=$array[1];//Silva

?>

By your comment, you could do this:

<?php
 $limite=2;
for($i=0;$i<$limite-1;$i++){
$novoArray[]=$array[$i];
}?>

This is the way I thought and I have it at the moment, there may be others, but this is the only one I thought and I do not think I need to test. This new array will be the new array, with the amount of items you set in the $ limit. I hope I have helped

    
17.07.2016 / 16:43
1

Simple

$teste['nome'] = $array['nome'];
$teste['snome'] = $array['snome'];

Using the array_slice()

$array = array('nome' => 'foo', 'snome' => 'bar', 'test' => 'ok');
print_r(array_slice($array, 0, 2, true));

Demo: link

    
17.07.2016 / 23:01