PHP create array where key and value is same - php

I am using the range() function to create an array. However, I want the keys to be the same as the value. This is ok when i do range(0, 10) as the index starts from 0, however if i do range(1, 11), the index will still start from 0, so it ends up 0=>1 when i want it to be 1=>1
How can I use range() to create an array where the key is the same as the value?

How about array_combine?
$b = array_combine(range(1,10), range(1,10));

Or you did it this way:
$b = array_slice(range(0,10), 1, NULL, TRUE);
Find the output here: http://codepad.org/gx9QH7ES

There is no out of the box solution for this. You will have to create the array yourself, like so:
$temp = array();
foreach(range(1, 11) as $n) {
$temp[$n] = $n;
}
But, more importantly, why do you need this? You can just use the value itself?

<?php
function createArray($start, $end){
$arr = array();
foreach(range($start, $end) as $number){
$arr[$number] = $number;
}
return $arr;
}
print_r(createArray(1, 10));
?>
See output here: http://codepad.org/Z4lFSyMy

<?php
$array = array();
foreach (range(1,11) as $r)
$array[$r] = $r;
print_r($array);
?>

Create a function to make this:
if (! function_exists('sequence_equal'))
{
function sequence_equal($low, $hight, $step = 1)
{
return array_combine($range = range($low, $hight, $step), $range);
}
}
Using:
print_r(sequence_equal(1, 10, 2));
Output:
array (
1 => 1,
3 => 3,
5 => 5,
7 => 7,
9 => 9,
)
In PHP 5.5 >= you can use Generator to make this:
function sequence_equal($low, $hight, $step = 1)
{
for ($i = $low; $i < $hight; $i += $step) {
yield $i => $i;
}
}

Related

How to get array min value

I have multidimensional array and me need to get a minimum value.
Array may be [65,4,4,511,5,[[54,54[.[.[..].].]] and so on.
example code
<?php
$arr = [5, 1 , 2, 3, [1,5,59,47,58,[0,12,562]]];
function NumMin($arr)
{
$num = '';
foreach ($arr as $item => $i) {
if(is_array($i)){
NumMin($i);
}
else{
$num .= $i.',';
}
}
$num .= $num;
return $num;
}
$g = NumMin($arr);
var_dump($g);
I need to get 0
You can use array_walk_recursive() function to flatten a given array (makes it one-dimensional).
And use simply min() function for getting the desired output after.
array_walk_recursive($arr, function($v) use (&$res){
$res[]=$v;
});
echo min($res);
Demo
<?php
$GLOBALS["min"] = 999999; //min value int
$arr = [[[5,6],7],9,7,5, 1 , 2, 3, [1,5,59,47,58,[1,12,562]]];
array_walk_recursive($arr, 'NumMin');
function NumMin($item)
{
if(intval($item) <= intval($GLOBALS["min"]))
{
$GLOBALS["min"] = intval($item);
}
}
// The end, $GLOBALS["min"] will have the least value
echo $GLOBALS["min"];
?>

Select only elements you want in string/array

I have an array like this $arr = array(2, -3, 6, 1);
And I only want to select the positive numbers to be able to sum the others between them.
So I wrote this code, but I'm a bit lost on how to select the elements I only want to do something with them, like summing them.
$sum = implode(",", $arr);
for($i = 0; $i <= strlen($sum); $i++) {
if($i <= 0) {
} else {
return explode(",", array_sum($i));
}
}
}
Use array_fliter to filter the value, and array_sum to sum the array.
array_sum(array_filter($array, function($v){return $v>0;});
Use array_filter with callback function like below :
<?php
$arr = array(2, -3, 6, 1);
function positive($a){
if($a > 0){
return $a;
}
}
$newArr = array_sum(array_filter($arr, "positive"));
print_r($newArr);
?>
Using array_reduce:
$arr = array(2, -3, 6, 1);
$result = array_reduce($arr, function($c, $i) { return $i > 0 ? $c + $i : $c; });
echo $result;

php get MIN and MAX from loop results

I have this loop and im wondering how can i get the MIN and MAX value inside the loop:
foreach($result_1 as $key_1) {
if($key_1->ordering > $key_0->ordering ) {
echo $key_1->ordering;
}
}
RESULT : 234
RESULT WANTED IS MIN (2) AND MAX (4) VALUES
Sounds like a good job for the functional reduce approach. You can do this in PHP with the array_reduce function:
You pass in an array, a callback and a starting value and the function will call the callback with the current value and the next item from the array and store the result.
php> $array = [ 6, 2, 8, 4 ];
array (
0 => 6,
1 => 2,
2 => 8,
3 => 4,
)
php> array_reduce($array, 'min', reset($array));
int(2)
php> array_reduce($array, 'max', reset($array));
int(8)
In this example I used min and max respectively as the callback and the first array item as the starting value.
In order to use this properly on your array you can pass in a custom callback using an anonymous function:
function ($a, $b) {
return max($a->ordering, $b->ordering);
}
You just need to loop through the array once and check every value against the current minimum/maximum, and replace it if it is smaller/bigger.
$min = reset( $array )->ordering; // Assign any value to start (just the first in this case)
$max = reset( $array )->ordering; // Assign any value to start (just the first in this case)
foreach ( $array as $object ) {
//max
if( $object->ordering > $max ) {
$max = $object->ordering;
}
//min
if( $object->ordering < $min ) {
$min = $object->ordering;
}
}
echo $min;
echo $max;
Just use the min($result_1) and max($result_1) functions that are built into PHP.
http://us2.php.net/max
http://us2.php.net/min
Edit:
Since it's an array of objects, try using two temporary variables to keep track of the min and max. I'm assuming in this code you're looking for the max and min ordering.
$min = 1000000;
$max = -1000000;
foreach($result_1 as $key_1) {
if($key_1->ordering > $max ) {
$max = $key_1->ordering;
}
else if($key_1->ordering < $min) {
$min = $key_1->ordering;
}
}
echo $min;
echo $max;
You can take the logic of a selection sort and use it to find the minimum value. I'm sure you can figure out from this code how to find the max.
$min = 0;
foreach($result_1 as $key_1) {
$min = $key_1->ordering
foreach($result_1 as $key_2) {
if($min > $key_2->ordering) {
$min = $key_2->ordering;
}
}
}
Here is my test:
$data = array(
5,
6,
7,
1,
9,
11,
3
);
$min = 0;
foreach($data as $key => $value) {
$min = $value;
foreach($data as $key2 => $value2) {
if($min > $value2) {
$min = $value2;
}
}
}
echo $min . "\n"; // 1

PHP: Take several arrays, and make new ones based on shared indexes? [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Is there a php function like python's zip?
(14 answers)
Closed 10 months ago.
So, imagine you have 3 arrays:
1,2,3,4,5
6,7,8,9,10
11,12,13,14,15
And you want to combine them into new arrays based on index:
1,6,11
2,7,12
3,8,13
4,9,14
5,10,15
What on earth could achieve this? Also, the total number of arrays is not known.
EDIT: Here's a snippet of my code so far (pulling data from a DB):
<?php
$ufSubmissions = $wpdb->get_results( $wpdb->prepare("SELECT * FROM wp_user_feedback WHERE user = '$ufUser' ORDER BY date DESC") );
$cleanedResponses = array();
foreach ($ufSubmissions as $submission) {
$cleanedResponses[] = unserialize($submission->responses);
}
array_map(null, $cleanedResponses));
?>
Doesn't seem to be working though, even $cleaned responses is an array of arrays.
Mostly like Alex Barrett's answer, but allows for an unknown number of arrays.
<?php
$values = array(
array(1,2,3,4,5),
array(6,7,8,9,10),
array(11,12,13,14,15),
);
function array_pivot($values)
{
array_unshift($values, null);
return call_user_func_array('array_map', $values);
}
print_r(array_pivot($values));
If your arrays are all the same length, you can pass as many as you want to the array_map function with null as the callback parameter.
array_map(null,
array(1, 2, 3, 4, 5),
array(6, 7, 8, 9, 10),
array(11, 12, 13, 14, 15));
The above will return the following two-dimensional array:
array(array(1, 6, 11),
array(2, 7, 12),
array(3, 8, 13),
array(4, 9, 14),
array(5, 10, 15));
This is a documented trick, so quite safe to use.
$ret = array();
for ($i =0; $i < count($input[0]); $i++){
$tmp = array();
foreach ($input as $array) {
$tmp[] = $array[$i];
}
$ret[] = $tmp;
}
Em... What's the problem? If they are equal sized, then you do
<?php
$a = array(1,2,3,4,5);
$b = array(6,7,8,9,10);
$c = array(11,12,13,14,15);
$d = array();
for ($i = 0; $i < sizeof($a); $i++) {
$d[] = array($a[$i], $b[$i], $c[$i]);
}
var_dump($d);
This is not tested, read it to get the idea instead of paste it.
The point is to put everything alltoghether in a feed and then redistribute it onto new arrays of a max length, the last one could not be full.
<?php
// initial vars
$max_size = 3; // of the new arrays
$total_array = $a + $b + $c; // the three arrays summed in the right order
$current_size = length($total_array);
$num_of_arrays = ceil($current_size / $max_size);
// redistributing
$result_arrays = array();
for($i = 0; $i < $num_of_arrays; $i++){ // iterate over the arrays
$new_array= array();
for($t = 0; $t < $max_size){
$pos = $num_of_arrays * $t + $i;
if(isset($total_array[$pos]) {
$new_array[] = $total_array[$pos];
}
}
$result_arrays[] = $new_array;
}
?>
// This takes an unlimited number of arguments and merges into arrays on index
// If there is only 1 argument it is treated as an array of arrays
// returns an array of arrays
function merge_on_indexes () {
$args = func_get_args();
$out = array();
if (count($args) == 1) for ($i = 0; isset($args[0][$i]); $i++) for ($j = 0; isset($args[0][$i][$j]); $j++) $out[$j][] = $args[0][$i][$j]; else for ($i = 0; isset($args[$i]); $i++) for ($j = 0; isset($args[$i][$j]); $j++) $out[$j][] = $args[$i][$j];
return $out;
}
// Usage examples
// Both return array('data1','data3','data5'),array('data2','data4','data6')
$arr1 = array('data1','data2');
$arr2 = array('data3','data4');
$arr2 = array('data5','data6');
$result = merge_on_indexes($arr1,$arr2);
print_r($result);
$multiDimArr = array(
array('data1','data2'),
array('data3','data4'),
array('data5','data6')
);
$result = merge_on_indexes($multiDimArr);
print_r($result);
$arr = get_defined_vars(); //gets all your variables
$arrCount = 0;
$arrOfarrs = array();
foreach($arr as $var){ //go through each variable
if(is_array($var)){ //and see if it is an array
$arrCount++; //we found another array
for($i == 0;$i < count($var); $i++){ //run through the new array
$arrOfarrs[$i][] == $var[$i]; //and add the corresponding elem
}
}
}

PHP: Minimum value in 2D array

I have a 2D array in the format:
[
[1, 23, 20],
[2, 45, 30],
[4, 63, 40],
...
]
I am trying to search the array and return elements [0] and [1] from the row where element [1] is lowest. I have the following code to return the lowest value in [1] but I'm not sure how to get element [0] as well.
$min = PHP_INT_MAX;
foreach ($test as $i) {
$min = min($min, $i[1]);
}
In the above example I would return [1, 23]
Thanks,
You should use usort for this:
usort($test, function($a, $b) {
return $a[1] - $b[1];
});
$min = $test[0];
Note that this uses anonymous functions, which were introduced in PHP 5.3. In previous versions, you need to use named functions and pass the name as a string to usort.
You could use array_reduce:
$array = array(
array(1, 23, 20),
array(2, 45, 63),
array(4, 63, 40),
);
$callback = function ($a1, $a2) {
if ($a1[1] >= $a2[1]) {
return $a2;
} else {
return $a1;
}
}
$min = array_reduce($array, $callback, array(0, PHP_INT_MAX, 0));
var_dump($min); // array(1, 23, 20);
Now, this will likely have issues if you have multiple elements with identical [1] elements... But it transparently handles the case where the array is empty. And in general, all you need to do is do your comparison in the callback function for all "filtering" type problems where you can abstract the filtering to a comparison of 2 elements. So you do string comparison, etc to determine which of the 2 is better...
And it should be more efficient than a sort, since it only requires a single pass over the array (It's O(n) whereas sorting is O(n log n) and at worst O(n^2))...
This will do the job.
$min0 = PHP_INT_MAX;
$min1 = PHP_INT_MAX;
foreach ($test as $i) {
if($i[1] < $min1)
{
$min0 = $i[0];
$min1 = $i[1];
}
}
This will result in $min0 == 1 and $min1 == 23
You'll need to introduce some basic logic:
$result = array(0, PHP_INT_MAX);
foreach($test as $i)
if($i < $result[1])
$result = array($i[0], $i[1]);
You can use a simple min (O(n)) loop like you did, and array_slice to assign the first two indexes when a lowest is found :
$min = PHP_INT_MAX;
$arrMin = array();
foreach ($test as $i) {
if ($i[1] < $min) {
$min = $i[1];
$arrMin = array_slice($i, 0, 2);
}
}
you should just grab the array key of the smallest number:
$min = PHP_INT_MAX;
$minkey = 0;
foreach ($test as $key => $i) {
if($min > $i[1]) {
$min = $i[1];
$minkey = $key;
}
}
then, you can just access the whole thing with $test[$minkey]

Categories