delete array value and then compact - php

I want to delete a value of a numbered index's array, and then compact the array so the left index is not empty. This is my code but i'd like to know if there is an array method which do that
for ($j = 30; $j < count($a); $j++) {
if ($j+1 < count($a)) {
$a[$j] = $a[$j+1];
}
}
array_pop($a);
So this code remove the value of index 30 of the array and compact the array.
I could use unset(a[30]) but that left me with an array with no index 30. And I can't iterate correctly that array.

You can iterate the array using foreach however to answer the index question:
unset($a[30]);
$a = array_values($a);
You might also use:
array_splice($a, 30, 1);

Related

Find index if values in single array on either side are equal when summed

I have a whiteboard question that I think is way beyond my skill and so don't even know how to approach this.
I want to iterate through each value and sum the elements on left/right side and if they're equal return the index value.
So:
[1, 2, 3, 4, 3, 2, 1]; // return 3
The official question:
You are going to be given an array of integers. Your job is to take
that array and find an index N where the sum of the integers to the
left of N is equal to the sum of the integers to the right of N. If
there is no index that would make this happen, return -1.
Is anyone kind enough to help me out? I've looked at array_map() and array_filter() and while helpful I can't think of how to traverse back and forth between the current index when iterating the array.
This can be done with a simple for loop over the full range of an array combined with array_slice and array_sum.
function doSomething(array $data): int {
for ($i = 0, $count = count($data); $i < $count; $i++) {
$left = $i > 0 ? array_slice($data, 0, $i) : [ $data[0] ];
$right = $i > 0 ? array_slice($data, $i + 1) : $data;
$left_result = array_sum($left);
$right_result = array_sum($right);
if ($left_result === $right_result) {
return $i;
}
}
return -1;
}
This small piece of code loops over the whole array and sums up the left and the right of the current position of the array. The results will be compared and if the results are the same, the key of the array will be returned.
For huge arrays you can try to reduce memory consumption by using a yield or an Iterator instance.

PHP: Fill multidimensional array at specific positions recursively

I need to fill a multidimensional array with simple arrays recursively at positions specified by for loops, and that need to be done with the same multidimensional array.
The first time the multid. array is filled is in the code below
$vector_provisor = array ();
for ($i = 0; $ i <variable_variable; $i++)
{
array_push($vector_temp, 0);
}
$ element_pivot =$ lines [$index_line_pivot] [$index_column_pivo];
for ($j = 0, $j <dim - 1, j++)
{
$value = $rows [$index_line_pive] [$j] / $element_pivot;
array_push ($vector_provisor, $ value);
$index = array ($index_line_pivot);
}
#that's the array filled:
$new_lines {$index} = array_fill_keys ($index, $vector_provisor);
Now let's say the first time it filled position [1], if I try to repeat that, in another for loop, for positions [1] and [2], but without creating the array again, it simply empties all the positions and I got an empty array.
What could I do?

Combine two assosiative array's if (id) value are the same

So I got two associative arrays containing key-value pairs. They share one key name, and I want to add one array to the other if the "name" values are equal.
So if you have these arrays:
$array1 = [name=>"Foo",
date=>array("2016-06-06", "2016-06-05", "2016-06-04"),
(some other key-value pairs)];
$array2 = [name=>"Foo",
date=>array("2016-06-06", "2016-06-05", "2016-06-04"),
download_count=>array(54,23,15),
(some other key-value pairs)];
the result should be something like this:
$newArray = [name=>"Foo",
date=>array("2016-06-06", "2016-06-05", "2016-06-04"),
(the other key-value pairs from $array1),
app=>array(
name=>"Foo",
date=>array("2016-06-06", "2016-06-05", "2016-06-04"),
download_count=>array(54,23,15),
(the other key-value pairs from $array2))]
Right now I try to loop through both of the array's to see where the names of both array's at index $i,$j are the same, and if they are combine the two.
Here is the code I use for that
foreach($array1 as $foo){
foreach($array2 as $bar){
if($foo["name"] == $bar["name"]){
$foo["app"] = $bar;
}
}
}
alternatively I tried with just regular for loops like this:
for($i = 0; $i < count($array1); $i++){
for($j = 0; $j < count($array2); $i++){
if($array1[$i]["name"] == $array2[$j]["name"]){
$array1[$i]["app"] = $array2[$j];
break;
}
}
}
The result from the first example is just $array1 (unchanged), and the result form the alternative example is an infinite loop.
Could someone help figure out how to get the desirable result?
Edit
Got it working, was just a beginners error in this case both for loops increased $i by one instead of the first loop adding one to $i and the other adding ine to $j

How I can show only three elements of my associative array using for?

This is my Associative Array:
$vetor = array(
"Name"=> "myName",
"Tel"=> "555-2020",
"Age"=> "60",
"Gender"=> "Male"
);
How I can show only three elements using the loop for?
I tried this:
for($i=0; $i<=2; $i++){
echo $vetor[$i]."<br>";
}
But without success. How I can do this?
You referring to wrong indexes because to reference the first element on your array you have to do something like : $vetor["Name"] instead of $vetor[0]
$i = 0;
foreach($vetor as $key => $value){
if($i == 2){ break; }
echo $value;
$i++;
}
foreach makes more sense for an array like this, but if you want to use for for whatever reason, the problem you'll have is that the array doesn't have sequential numeric indexes that correspond to your loop increment variable. But there are other ways to iterate over the first three elements without knowing what the indexes are.
// this first step may not be necessary depending on what's happened to the the array so far
reset($vetor);
$times = min(3, count($vetor));
for ($i = 0; $i < $times; $i++) {
echo current($vetor).'<br>';
next($vetor);
}
If next moves the internal array pointer beyond the last array element, current($vetor) will return false, so setting $times using min with the number of times you want and the array count will prevent you from looping more times than there are items in the array.
Another way, if you don't care what the keys are, is to use array_values to convert the array keys to numbers.
$vetor = array_values($vetor);
for ($i=0; $i < 3; $i++) {
echo $vetor[$i].'<br>';
}

Sort 2-dimensional array by elements of inner arrays

I have an Array with 8 arrays inside.
It looks like this:
[[num,...],[num,...],[num,...],[num,...],[num,...],[num,...],[num,...],[num,...]]
Each of this inner arrays has as its first element a number. Now I want to receive the element of the outer array with the biggest number as first element.
How do I do that?
Thank you very much.
You can define any sorting algorithm by using PHP's usort()
usort($array, function($a, $b) {
return $a[0] > $b[0];
});
This will sort your array, in place, such that the first element will have the largest number as it's first element.
It's not necessary (and is much more expensive) to sort the entire array. Something like this would work:
// initially, regard the first element as the largest
$element = $array[0];
$greatest = $array[0][0];
$length = count($array);
// compare the first value of each array against $greatest, swapping $element if it's larger
for($i = 1; $i < $length; $i++) { // N.B. start with second element
if($array[$i][0] > $greatest) {
$element = $array[$i];
}
}
// $element is now the element with the biggest first value
Check out usort : http://php.net/manual/en/function.usort.php
You'll have to write your own comparison function.

Categories