How to split array into two different array - php

How to split array into two different array and return both. here my array is $input , it may contain any number of element.
for example:
$input = array ('onex','twox','threex','fourx','fivex','sixx','sevenx','eightx','ninex');
I want to split my '$input' array into two different array '$number1' and '$number2' .
1)if $input array with even element then split into 2 equal element arrays.
2)if $input array with odd element then '$number1' is always 1 element greater than '$number2' .

You can use array_chunk for it.
$new_arrays = array_chunk($input, ceil(count($input)/2));
$number1 = $new_arrays[0];
$number2 = $new_arrays[1];

Related

How to merge two two dimensional arrays with the same number of elements per sub array in php?

I need to merge the second array into the first. For example the first array is
$data_array = array
(
array('Ford','Escape','25000','new')
);
The second array is
$new_array = array
(
array('Toyota','Camry','12000','used')
);
For merging the two arrays I tried
$data_array = array_merge($data_array[0],$new_array[0]);
print_r($data_array);
This combines the two arrays into one row array. What I want is to create two rows, each containing one of those arrays.
Sample result:
array(array('Ford','Escape','25000','new'),array('Toyota','Camry','12000','used'))
You have to assign the merged result. Pay attention to the function signature and description in the manual for array_merge():
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
$merged_array = array_merge($data_array[0],$new_array[0]);
print_r($merged_array);
You could call it $data_array and overwrite the existing one:
$data_array = array_merge($data_array[0],$new_array[0]);
print_r($data_array);
Or even $data_array[0]:
$data_array[0] = array_merge($data_array[0],$new_array[0]);
print_r($data_array);
Contrast this with something like sort():
bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
Where the bool means that it returns true or false and the & preceding $array means that the array is passed by reference and modified.
However, after your edit it seems that you want the two rows in your original arrays to be two rows in a new array, so just don't specify the index [0]:
$data_array = array_merge($data_array,$new_array);
print_r($data_array);

In php How i divide a array by user input for make it to another some arrays

Suppose my array is:
$letters = array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");
and user input is:
$number = "4";
Now how i convert this array on look like that:
$array1 = array("a","b","c","d");
$array2 = array("e","f","g","h");
$array3 = array("i","j","k","l");
Try http://php.net/array_chunk
If you want to split the array in 4 then your code should look like this.
$output_array=array_chunk($letters, 4);
This will return you two dimensional array having chunks of array of 4 key,value pairs.
Use array_chunk — Split an array into chunks:
Ex
array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )
So Use
array_chunk($letters,4,true)

PHP make N copies of array with functions

In my code I need to make a number of copies of a dummy array. The array is simple, for example $dummy = array('val'=> 0). I would like make N copies of this array and tack them on to the end of an existing array that has a similar structure. Obviously this could be done with a for loop but for readability, I'm wondering if there are any built in functions that would make this more verbose.
Here's the code I came up with using a for loop:
//example data, not real code
$existingArray = array([0] => array('val'=>2),[1] => array('val'=>3) );
$n = 2;
for($i=0;$i<$n;$i++) {
$dummy = array('val'=>0); //make a new array
$existingArray[] = $dummy; //add it to the end of $existingArray
}
To reiterate, I'd like to rewrite this with functions if such functions exist. Something along the lines of this (obviously these are not real functions):
//make $n copies of the array
$newvals = clone(array('val'=>0), $n);
//tack the new arrays on the end of the existing array
append($newvals, $existingArray)
I think you're looking for array_fill:
array array_fill ( int $start_index , int $num , mixed $value )
Fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter.
So:
$newElements = array_fill(0, $n, Array('val' => 0));
You do still have to handle the appending of $newElements to $existingArray yourself, probably with array_merge:
array array_merge ( array $array1 [, array $... ] )
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
So:
$existingArray = array_merge($existingArray, $newElements);
This all works because your top-level arrays are numerically-indexed.

Convert Array into Key Value Pair array

I have a comma separated string which i explode into an array. If the array is of un-known length and i want to make it into a key value pair array where each element in the array has the same key, how do i do this? i'm assuming i'd have to use array_combine? can anyone give me an example using the array bellow? :
for instance:
array([0]=>zebra, [1]=>cow, [2]=>dog, [3]=>monkey, [4]=>ape)
into:
array([animal]=>zebra, [animal]=>cow, [animal]=>dog, [animal]=>monkey, [animal]=>ape)
You can't use the same key for each element in your array. You need a unique identifier to access the value of the array. When you use animal for all, what value should be used? What you can do is to make a 2 dimensional array that you have an array inside an array:
array(
[animals] => array(
[0]=>zebra, [1]=>cow, [2]=>dog, [3]=>monkey, [4]=>ape
)
)
this can be used with $array['animals'][0]
But still you need numbers or unique identifiers to access the values of the array.
Something like this:
$string = 'zebra,cow,dog,monkey,ape';
$array = explode(',', $string);
$arrayReturn['animals'] = $array;
print_r($arrayReturn);
u cant have same key for all the values but u can do this
lets say your string is
$a = 'dog,ant,rabbit,lion';
$ar = explode(',',$a);
$yourArray = array();
foreach($ar as $animals){
$yourArray['animals']=$animals;
}
Now it doesnot matter how long your string is you will have you array as
$yourArray['animals'][0]='dog'
$yourArray['animals'][1]='ant'
....... so on ......

Splitting an array equally:

I have the following array:
$array = array(1,0,0,0,1,1,1,1,0,1,1,1,1,0,1,1,0,1,0,0,1,0,1);
I want split it up into individual arrays so that each array contains seven or less values.
So for example the first array will become:
$one = array(1,0,0,0,1,1,1)
$two = array(1,0,1,1,1,1,0)
$three = array(1,1,0,1,0,0,1);
$four = array(0,1);
Also how would you count the number of times 1 occurs in array one?
array_chunk() is what you are looking for.
$splitted = array_chunk($array, 7);
For counting the occurences I would be lazy. If your arrays only contain 1s or 0s, then a simple array_sum() would do:
print array_sum($splitted[0]); // for the first chunk
I want split it up into individual arrays so that each array contains seven or less values.
Use array_chunk(), which is made expressly for this purpose.
Also how would you count the number of times 1 occurs in array one?
Use array_count_values().
$one = array(1,0,0,0,1,1,1);
$one_counts = array_count_values($one);
print_r($one_counts);
// prints
Array
(
[0] => 3
[1] => 4
)
Assuming you want to preserve the contents of the array, I'd use array_slice() to extract the needed number of elements from the array, incrementing the '$offset' by the required count each time until the array was exhausted.
And as to your second question, try:
$num_ones=count(preg_grep(/^1$/,$array));

Categories