PHP: how to 'cut' my array? - php

I have an array
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
)
How can I remove the latest 2 cells and make it shorter ?
Array
(
[0] => 0
[1] => 1
[2] => 2
)
Thanks

Check out array_slice()
So, if you wanted the first three elements only:
$array = array_slice($array, 0, 3);
If you wanted all but the last three elements:
$array = array_slice($array, 0, -3);
The second parameter is the start point (0 means to start from the begining of the array).
The third parameter is the length of the resulting array. From the documentation:
If length is given and is positive, then the sequence will have that many
elements in it. If length is given and is negative then the sequence will
stop that many elements from the end of the array. If it is omitted, then
the sequence will have everything from offset up until the end of the array.

Slice it. With a knife.
Actually, with this:
array_slice($array, 0, -3);
Assuming you meant cutting off the last 3 elements.

Use array_splice():
$new = array_splice($old, 0, 3);
The above line returns the first three elements of $old.
Important: array_splice() modifies the original array.

Use array_splice as:
$array = array(0,1,2,3,4,5);
array_splice($array,0,3);

http://dev.fyicenter.com/faq/php/php_array_function_6.php
Look at the one about truncating, particularly array_splice

Related

PHP is possible to implode ignoring specific array?

I have an array that looks like this:
Array
(
[0] => 41
[1] => 43
[2] => 44
[comment] =>
)
is there any way to implode this array ignoring ['comment']??
Now ['comment']doesn't has content but sometimes it can have content. I need to ignore ['comment'] always.
Also ['comment'] will be always the last array.
Simply use unset and implode
unset($arr['comment']);
echo implode(',',$arr);
Demo
Use a negative offset with array_splice to remove the last element of the array.
$string = implode(',', array_splice($array, -1));

array_chunk reseting id in each array position

I created a array which stores XML elements in it.
$itemArray = array();
$itemArray[] = array ('[{id:'.$item.'species:'.$gender.'}]');
Now I used array_chunk to split the Array in 3 item parts.
$arrayChunked = array_chunk($itemArray, 3, true);
If I use:
var_dump($arrayChunked);
then the stored Items look like this:
0 => array(0,1,2)
1 => array(3,4,5)
2 => array(6,7,8)
But i need them stored like:
0 => array(0,1,2)
1 => array(0,1,2)
2 => array(0,1,2)
Any Idea of how i could do this?
Stop passing "true" as the third argument; you're telling it to preserve the original keys. If you take that out, it will reindex it automatically (as noted in the array_chunk docs).
i.e.
$arrayChunked = array_chunk($itemArray, 3);

Populating an array with a predefined set of numbers in PHP

I need to create two arrays, for simulating a draw from a Lotto ticket.
The first array will consist of 6 unique numbers between 1 and 49.
The second array will consist of 7 unique numbers between 1 and 49.
I'm fairly new to PHP and I can't figure out how to populate an array, give it a predefined size, randomly put six numbers between 1 through 49 into the array, and then finally sort the array's in ascending order.
This is my quick rough draft of what I think is somewhat heading in the right direction?
$tmp;
$lotto = array(rand(1,49)); //Creating the random number for $lotto
$lottoMax = array(rand(1,49)); //Creating the random number for $lottoMax
for($tmp=0; $lotto <= 6; $tmp++){
//creating the size of the array?
}
Any advice/tips/help would be greatly appreciated!
Thank you.
There are several ways to approach something like this. The first that comes to mind is to first just create an array of the numbers 1-49 using range(1, 49). Then shuffle the array with shuffle() so its order is randomized. Finally, since it is already randomized, you can just chop off the first 6 or 7 numbers to fill your two arrays (which I'll do with array_slice()). The contents are guaranteed not to have any repeats and it only takes a couple of operations.
// The bag of numbers is a range
$bag = range(1, 49);
// Shuffle it
shuffle($bag);
// Get the first array
$first_group = array_slice($bag, 0, 6);
// Shuffle it again and get the second array
shuffle($bag);
$second_group = array_slice($bag, 0, 7);
print_r($first_group);
Array
(
[0] => 36
[1] => 22
[2] => 34
[3] => 17
[4] => 23
[5] => 25
)
print_r($second_group);
Array
(
[0] => 40
[1] => 32
[2] => 33
[3] => 36
[4] => 29
[5] => 7
[6] => 3
)
You could just generate the initial numbers by range() function from 1 to 49, then shuffle, then slice it:
$first = range(1, 49); shuffle($first);
$second = range(1, 49); shuffle($second);
$lotto = array_slice($first, 0, 6);
$lottoMax = array_slice($second, 0, 7);
The array_rand() function returns a random selection from an array.
$all_numbers = range(1, 49); // Create an array of 1 .. 49
$pick6 = array_rand($all_numbers, 6);
sort($pick6);
$pick7 = array_rand($all_numbers, 7);
sort($pick7);
You seem to have a decent development background, which can make PHP arrays a little confusing at first. It helps me to think of them as hashes.
You can create an array in a few ways, I usually like to declare it:
$new_array = array();
or, to populate and initialize:
$new_array = array(1,2,3,"String")
PHP arrays are usually (always?) dynamically sized and typed...you can mix them up as much as you want.
You can also quickly add an item to an array by assignment:
$new_array[] = "whatever"; //will add it to the end of the array
$new_array['index'] = "more whatever"; // will insert it with the index 'index'
$new_array[11] = "last whatever"; // will put it in at numeric index 11
The latter two will overwrite any value in that index, which is probably obvious.
Anyway - hope that helps, and wasn't too obvious from the other answers already.
Here was what I had planned to suggest, but everyone beat me to it:
$possible_values = range(1,49);
$array_of_six = array_rand($possible_values,6);
$array_of_seven = array_rand($possible_values,7);
it comes back sorted by default.

PHP: how to add array index then cut into several array?

I have make many changes but still cannot figure out.
i have an array let say: [1,2,3,4,5,6,7,8,9,10]
i just want to ask how to add this array until index 2 and continued add for rest array then divide them by 2 array each.
input : [1,2,3,4,5,6,7,8,9,10 ];
process : [1+2+3, 4+5+6, 7+8+9, 10]
output i need : [6,15,24,10]
then i want to cut this array into 2
last output : [[6,5],[24,10]]
Thanks
Your code will be:
$data = range(1,10);
$result = array_chunk(array_map('array_sum', array_chunk($data, 3)), 2);
-please, read array functions manual
Something like this?
<?php
$array = range(1, 10);
$array = array_chunk($array, 3);
$array = array_map('array_sum', $array);
$array = array_chunk($array, 2);
print_r(
$array
);
/*
Array
(
[0] => Array
(
[0] => 6
[1] => 15
)
[1] => Array
(
[0] => 24
[1] => 10
)
)
*/
I think you can use a for cycle to sum what you need then store result in new array. Another solution is using array merge. When you've done the trick you can create a multidimensional array to get the result like [[6,5],[24,10]].
Hope it helps
Can't really see what you are getting at from the question, but I think PHP's array_chunk command may be your friend on this, http://www.php.net/manual/en/function.array-chunk.php
this will allow you to split the array into chunks of 3 (or any number) of elements with last element containing the remainder (in this case 1 element)

Remove Values from PHP Array if Present

I have the following PHP array:
Array
(
[0] => 750
[1] => 563
[2] => 605
[3] => 598
[4] => 593
)
I need to perform the following action on the array using PHP:
Search the array for a value (the value will be in a
variable; let's call it $number). If the value
is present in the array, remove it.
If someone could walk me through how to do that, it would be much appreciated.
Note: If it makes it any easier, I can form the array so the keys are the same as the values.
$array = array_unique($array) // removes dupicate values
while(false !== ($num = array_search($num, $array))){
unset($array[$num]);
}
$max = max($array);
will search for all keys with value $num and unset them
lets say your $array
$array = array_unique($array) // removes dupicate values
$array = arsort($array)
$variable = $array[0] // the maximum value in the array, and place it in a variable.
$key = array_search($array, $number);
if($key){
unset($array[$key]) // Search array for a value, value is present in array, remove it.
}
array_search() and unset() seems a good method for your sample data in your question. I'll just show a different way for comparison's sake (or in case your use case is slightly different from what you have posted here).
Methods: (Demo)
$array=[750,563,605,598,593];
// if removing just one number apply the number as an array element
$number=605;
var_export(array_diff($array,[$number]));
// if you are performing this task with more than one $number, make $numbers=array() and do the same...
$numbers=[605,563]; // order doesn't matter
var_export(array_diff($array,$numbers));
// if you need to re-index the output array, use array_values()...
$numbers=[605,563]; // order doesn't matter
var_export(array_values(array_diff($array,$numbers)));
Output:
array (
0 => 750,
1 => 563,
3 => 598,
4 => 593,
)
array (
0 => 750,
3 => 598,
4 => 593,
)
array (
0 => 750,
1 => 598,
2 => 593,
)

Categories