Limit the size of an array

Asked

Viewed 1,458 times

0

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

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

using all elements:

$user = $array;

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

$teste = ?

2 answers

3

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

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

?>

By your comment, you could do so:

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

This is the way I thought and I have at the moment, there may be others, but this is the only one I thought and I don’t think I need to test. This new array, will be the new array, with the amount of items that Voce set in the $limit. I hope I’ve helped

  • In fact, the two variables would return an array, only the second would be a "cut" array with the amount of elements I want to be the limit.

  • 1

    edited there, take a look if that’s it

  • 1

    I had this same idea, but I thought there should be some function that would already do this, and I found a call array_slice, which cuts the array and returns the elements you want, it served me, but thank you for your reply, thank you :)

  • 1

    You’re welcome, I thought you did, but I couldn’t test it here... but I’m glad you found

1

Simple

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

Using the function array_slice()

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

Demonstration: http://ideone.com/pndVWp

Browser other questions tagged

You are not signed in. Login or sign up in order to post.