I have a range of 67 numbers, something like 256 through to 323, which I want to add to an existing array. it doesn't matter what the values are.
looking for code to iterate through those numbers to add them as keys to the array without adding each one at a time
Try array_fill_keys and range
$existingArray = array('foo', 'bar', 'baz');
$existingArray += array_fill_keys(range(256,323), null);
Use whatever you like instead of null. You could also use array_flip() instead of array_fill_keys(). You'd get the index keys as values then, e.g. 256 => 1, 257 => 2, etc.
Alternatively, use array_merge instead of the + operator. Depends on the outcome you want.
you can use range() eg range(256,323)
push(); could be a look worth, or you can do it
like this
for($i=0;$i<count($array);$i++)
{
$anotherArray[$i] = $array[$i];
}
You can try using the range and array_merge functions.
Something like:
<?php
$arr = array(1,2,3); // existing array.
$new_ele = range(256,323);
// add the new elements to the array.
$arr= array_merge($arr,$new_ele);
var_dump($arr);
?>
Related
I have an array in the array, and I want to make it just one array, and I can easily retrieve that data
i have some like
this
but the coding only combines the last value in the first array, not all values
is it possible to make it like that?
so that I can take arrays easily
I would make use of the unpacking operator ..., combined with array_merge:
$array['test2'] = array_merge(...array_merge(...$array['test2']));
In your case you need to flatten exactly twice, if you try to do it one time too much it will fail due to the items being actual arrays themselves (from PHP's perspective).
Demo: https://3v4l.org/npnTi
Use array_merge (doc) and ... (which break array to separate arrays):
function flatten($arr) {
return array_merge(...$arr);
}
$arr = [[["AAA", "BBB"]], [["CCC"]]];
$arr = flatten(flatten($arr)); // using twice as you have double depth
In your case, $arr is $obj["test2"]. If your object is json cast it to array first and if it is a string use json_decode
Live example: 3v4l
if you have a array then you can use the below code
if(!empty($array['test2'])){
$newarray = array();
foreach ($array['test2'] as $arrayRow) {
$newarray = array_merge($newarray,$arrayRow);
}
$array['test2'] = $newarray;
}
I'm wondering what is the easiest/cleanest way to get an array of random values from an array in PHP. It's easy to get an array of random keys but it seems there's not function to get array of values straight away
The easiest way I found out is:
$tokens = ['foo', 'bar', '...'];
$randomValues = array_map(function($k) use ($tokens) {
return $tokens[$k];
}, array_rand($tokens, rand(7, 20)))
This returns 7-20 random values from $tokens variable. However this looks ugly and is very unclear at first sight what it does.
If you don't want to modify your $tokens array, you could flip your randomly generated array keys and then use array_intersect_key. I think it's a little more readable than the array_map method, but I suppose that's fairly subjective.
$randomKeys = array_flip(array_rand($tokens, rand(7, 20)));
$randomValues = array_intersect_key($tokens, $randomKeys);
If you don't care if $tokens is modified, the shuffle\slice method seems very straightforward.
Just shuffle and then slice a random number of elements:
shuffle($tokens);
$result = array_slice($tokens, 0, rand(7, 20));
If you don't want to modify the array then obviously just assign another variable and use that:
$temp = $tokens;
if I give you:
$array = array(object1, object2, object3, object4);
and say, at position 2, remove all elements before this position so the end result is:
$array = array(object3, object4);
What would I do? I was looking at array_shift and array_splice to achieve what I wanted - how ever I am not sure which to use or how to use them to achieve the desired affect.
Use array_slice. For more detail check link http://php.net/manual/en/function.array-slice.php
$array = array(object1, object2, object3, object4);
$array = array_slice($array,2); // 2 is position
Or if you are looking into the values instead of the index, with a tiny adjustment in #Ashwani's answer you can have:
$array = array('object1', 'object2', 'object3', 'object4');
$slice = array_slice($array, array_search('object3',$array));
array_slice is one way to go about it, however, if you are wanting to remove all the elements in an any array before a specific value, without searching, then:
//assuming you've already verified the match is in the array
//make a copy of $array first if you don't want to break the original
while($array[0] !== $match) {
array_shift(&$array);
}
Alternatively, you could:
$index = array_search($match, array_values($array));
if($index !== false) $array = array_slice($array, $index);
This accomplished both the verification and slice. Note the array_values() is used to account for associative arrays.
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.
Is there any simple way of checking if all elements of an array are instances of a specific type without looping all elements? Or at least an easy way to get all elements of type X from an array.
$s = array("abd","10","10.1");
$s = array_map( gettype , $s);
$t = array_unique($s) ;
if ( count($t) == 1 && $t[0]=="string" ){
print "ok\n";
}
You cannot achieve this without checking all the array elements, but you can use built-in array functions to help you.
You can use array_filter to return an array. You need to supply your own callback function as the second argument to check for a specific type. This will check if the numbers of the array are even.
function even($var){
return(!($var & 1));
}
// assuming $yourArr is an array containing integers.
$newArray = array_filter($yourArr, "even");
// will return an array with only even integers.
As per VolkerK's comment, as of PHP 5.3+ you can also pass in an anonymous function as your second argument. This is the equivalent as to the example above.
$newArray = array_filter($yourArr, function($x) { return 0===$x%2; } );
Is there any simple way of checking if all elements of an array [something something something] without looping all elements?
No. You can't check all the elements of an array without checking all the elements of the array.
Though you can use array_walk to save yourself writing the boilerplate yourself.
You can also combine array_walk with create_function and use an anonymous function to filter the array. Something alon the lines of:
$filtered_array = array_filter($array, create_function('$e', 'return is_int($e)'))