$arr = array('1st', '1st');
The above $arr has 2 items , I want to repeat $arr so that it's populated with 4 items
Is there a single call in PHP?
array_fill function should help:
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.
In your case code will look like:
$arr = array_fill(0, 4, '1st');
$arr = array('1st', '1st');
$arr = array_merge($arr, $arr);
This is a more general answer. In PHP 5.6+ you can use the "splat" operator (...) to repeat the array an arbitrary number of times:
array_merge(...array_fill(0, $n, $arr));
Where $n is any integer.
Related
I want to make an array with the same value and set the array to be maximum based on my counter.
For example, I want to create an array with a string "hello" and I want it to keep going until the number of array is 3.
How is that possible using php with yii2 framework?
you can use a for loop this way
$array= array();
for($i=0;$i<3;$i++){
$array[] = "hello";
}
You will get $array with 3 hello.
try array_fill
$count = 5;
$a = array_fill(0, $count, 'hello');
How can I delete duplicates in array?
For example if I had the following array:
$array = array('1','1','2','3');
I want it to become
$array = array('2','3');
so I want it to delete the whole value if two of it are found
Depending on PHP version, this should work in all versions of PHP >= 4.0.6 as it doesn't require anonymous functions that require PHP >= 5.3:
function moreThanOne($val) {
return $val < 2;
}
$a1 = array('1','1','2','3');
print_r(array_keys(array_filter(array_count_values($a1), 'moreThanOne')));
DEMO (Change the PHP version in the drop-down to select the version of PHP you are using)
This works because:
array_count_values will go through the array and create an index for each value and increment it each time it encounters it again.
array_filter will take the created array and pass it through the moreThanOne function defined earlier, if it returns false, the key/value pair will be removed.
array_keys will discard the value portion of the array creating an array with the values being the keys that were defined. This final step gives you a result that removes all values that existed more than once within the original array.
You can filter them out using array_count_values():
$array = array('1','1','2','3');
$res = array_keys(array_filter(array_count_values($array), function($freq) {
return $freq == 1;
}));
The function returns an array comprising the original values and their respective frequencies; you then pick only the single frequencies. The end result is obtained by retrieving the keys.
Demo
Try this code,
<?php
$array = array('1','1','2','3');
foreach($array as $data){
$key= array_keys($array,$data);
if(count($key)>1){
foreach($key as $key2 => $data2){
unset($array[$key2]);
}
}
}
$array=array_values($array);
print_r($array);
?>
Output
Array ( [0] => 2 [1] => 3 )
PHP offers so many array functions, you just have to combine them:
$arr = array_keys(array_filter(array_count_values($arr), function($val) {
return $val === 1;
}));
Reference: array_keys, array_filter, array_count_values
DEMO
Remove duplicate values from an array.
array_unique($array)
$array = array(4, "4", "3", 4, 3, "3");
$result = array_unique($array);
print_r($result);
/*
Array
(
[0] => 4
[2] => 3
)
*/
I have an array, and I don't know how may elements there are in the array. It could be 1, it could be 500, but I need the maximum amount to elements to be 21.
I know I can check the length using count(), but how do I chop the rest off if it is too long? Thanks.
You can use SplFixedArray it a good way to manage fixed size array .....
$array = new SplFixedArray(21);
Example
$array = SplFixedArray::fromArray($array);
$array->setSize(21);
See PHP Documentation
Try this code:
if(count($array) > 21){
$subarray = array_slice($array, 0, 21);
}
Explanation:
array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )
array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.
If your array is $arr then:
$subArray = array_slice($arr,0,21);
You can use array_slice to chop off the exceeding portion.
if(count($array) > 21){
$array = array_slice($array, 0, 21);
}
http://php.net/manual/function.array-slice.php
you need to use array_slice by specifying the offset as 0, and length as 21.
if(count($your_array) > 21){
$new_array = array_slice($your_array, 0, 21);
}
You can use array_splice to remove the elements beyond what you need
I am using str_split() to split a long strings into an array of length 16 each. And I'm assigning the returned array to one in my function. Like this:
$myarray = str_split($string, 16);
The problem is that I want the indexing of $myarray to start from a number other than 0, say 50. Currently I'm doing this:
foreach($myarray as $id => $value)
{
$myarray[$id + 50] = $value;
unset($myarray[$id]);
}
Is there a better solution? Because the arrays and strings I'm dealing with are very long. Thanks
You can use array_pad().
$myarray = str_split($string, 16);
$myarray = array_pad($myarray, -(size($myarray)+50), null);
It will fill the first 50 elements with nulls and push the rest of the array forward by 50 elements.
How can I add all of my array values together in PHP? Is there a function for this?
If your array consists of numbers, you can use array_sum to calculate a total. Example from the manual:
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";
If your array consists of strings, you can use implode:
implode(",", $array);
it would turn an array like this:
strawberries
peaches
pears
apples
into a string like this:
strawberries,peaches,pears,apples
if your array are all numbers and you want to add them up, use array_sum(). If not, you can use implode()
array_sum function should help. Here I presume your array comprises of integer or float values.
Let the given array values may contain integer or may not be.
It would be better to have check and filter the values.
$array = array(-5, " ", 2, NULL, 13, "", 7, "\n", 4, "\t", -2, "\t", -8);
// removes all NULL, FALSE and Empty Strings but leaves 0 (zero) values
$result = array_filter( $array, 'is_numeric' );
echo array_sum($result);