How can I keep only every second element from array usign PHP? - php

Below is a part of my produced array. How can I keep only every second element usign PHP?
I have tried this until now without luck, maybe it depends on the structure of the array, I didn't understand.
$size = count($array);
$result = array();
for ($i = 0; $i < $size; $i += 2) {
$result[] = $array[$i];
}
var_dump($result);
this is my array below:
Array
(
[0] => Array
(
[0] =>
11.490
[1] =>
11.490
[2] =>
13.490
[3] =>
13.490
[4] =>
17.490
[5] =>
17.490
[6] =>
20.990
[7] =>
20.990
[8] =>
14.290
[9] =>
14.290
[10] =>
14.490
[11] =>
14.490
[12] =>
19.990
[13] =>
19.990

Use array_filter (php.net)
function odd($var)
{
return($var & 1);
}
$array[0] = array_filter($array[0], "odd", ARRAY_FILTER_USE_KEY);
EDIT:
Of course you can also use an "even" method
EDIT 2:
Change to match the code from the op.
From $array to $array[0]
EDIT 3:
Add a missing semicolon

How about using unset on every other element?
<?php
$array = array('1','1','2','2','4','4','5','5');
for($i = count($array) - 1; $i > 0; $i -= 2){
unset($array[$i]);
}

Related

Filter array by skipping every nth element from the end

Is there an efficient way to get an array by skipping every n elements starting from the end (so that the last element is always in the result)?
Basically, I have a large array of 300k elements that I want to turn to 100k or 150k.
Sample input:
$array = array(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
Test: skip every other element
$x = 1;
Expected output:
$new_array = array(1,3,5,7,9,11,13,15);
Test: skip every second element
$x = 2;
Expected output:
$new_array = array(0,3,6,9,12,15);
Test: skip every third element
$x = 3;
Expected output:
$new_array = array(3,7,11,15);
Use a for() loop with a decrementing counter to allow you to push qualifying elements into the result array starting from the end of the array. To put the result array in the original order, just call array_reverse() after the loop.
Code: (Demo)
function skipFromBack(array $array, int $skip): array {
$result = [];
for ($index = array_key_last($array); $index > -1; $index -= 1 + $skip) {
$result[] = $array[$index];
}
return array_reverse($result);
}
Alternatively, you can pre-calculate the starting index, use an incrementing counter, and avoid the extra array_reverse() call. (Demo)
function skipFromBack(array $array, int $skip): array {
$increment = $skip + 1;
$count = count($array);
$start = ($count - 1) % $increment;
$result = [];
for ($i = $start; $i < $count; $i += $increment) {
$result[] = $array[$i];
}
return $result;
}
function skip_x_elements($array, $x)
{
$newArray = [];
$skipCount = 0;
foreach ($array as $value) {
if ($skipCount === $x) {
$newArray[] = $value;
$skipCount = 0;
} else {
$skipCount++;
}
}
return $newArray;
}
This should do what you want.
Improving upon #Dieter_Reinert answer, so you can also retain the keys inside said array, here is a slightly more flexible version that better fits the original question:
function skipX($array, $x, $grab = false){
$x = (!$grab) ? $x: $x - 1;
if($x <= 0) return $array;
$count = (count($array) % $x == 0) ? 0:$x;
$temparr = [];
foreach($array as $key => $value){
if($count === $x){
$temparr[$key] = $value;
$count = 0;
}else $count++;
}
return $temparr;
}
Example:
$array = range(0, 15);
foreach ([0, 1, 2, 3] as $skip){
print_r(skipX($array, $skip));
echo "\n---\n";
}
The correct output based on the original question:
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
[7] => 7
[8] => 8
[9] => 9
[10] => 10
[11] => 11
[12] => 12
[13] => 13
[14] => 14
[15] => 15
)
---
Array
(
[1] => 1
[3] => 3
[5] => 5
[7] => 7
[9] => 9
[11] => 11
[13] => 13
[15] => 15
)
---
Array
(
[2] => 2
[5] => 5
[8] => 8
[11] => 11
[14] => 14
)
---
Array
(
[0] => 0
[4] => 4
[8] => 8
[12] => 12
)
---
Online PHP Sandbox Demo: https://onlinephp.io/c/7db96

PHP make array element 1.5 bigger than previous one

I have a code below. It needs to make array element 1.5 bigger than previous one. Expected outcome should be ... 1, 1.5, 2.25, 3.375.. and so on but i get error (undefined offset)
$array= array();
for($i = 1; $i <= 10; $i++){
$array[$i] = $array[$i] * 1.5;
}
echo "<pre>";
print_r($array);
echo "</pre>";
But it doesn't seem to work. What my code should look like.
Your array is empty to start with, so $array[$i] * 1.5 will not work. Initialize your array with at least one number to start with. Use $array[$i-1] for the previous element
<?php
$array= array(1);
for($i = 1; $i <= 9; $i++){
$array[$i] = $array[$i-1] * 1.5;
}
print_r($array);
will output:
Array
(
[0] => 1
[1] => 1.5
[2] => 2.25
[3] => 3.375
[4] => 5.0625
[5] => 7.59375
[6] => 11.390625
[7] => 17.0859375
[8] => 25.62890625
[9] => 38.443359375
)

Appending each item in an array with multiple suffixes then make new array

I am trying to run an array through a for loop to append the items checked onto each array with each one appending the suffix with $n (1-3). Thank you for your suggestions I am one step closer, now I am getting each suffix on one item. I want each one as its own item in the array. Can anyone see the error?
I have updated my code and it is one step closer to the solution and underneath it is what I am aiming for.
$equip = 'Phone';
$ailments_checkvar = explode(', ', 'Cracked, Scratched, Bent, Twisted');
foreach ($ailments_checkvar as &$value) {
$value = 'directory/'.$equip.'_'.$value.'';
}
unset($value);
$duplicateArray = $ailments_checkvar;
foreach ($ailments_checkvar as $key) {
$duplicateArray[] = $key;
}
foreach ($ailments_checkvar as $key) {
$duplicateArray[] = $key;
}
for ($n = 1; $n <= 3; $n++) {
foreach ($duplicateArray as &$valueN) {
$valueN = $valueN.'_0'.$n.'.pdf';
}
}
unset($valueN);
print_r ($duplicateArray);
Getting this
Array ( [0] => directory/Phone_Cracked_01.pdf_02.pdf_03.pdf
[1] => directory/Phone_Scratched_01.pdf_02.pdf_03.pdf
[2] => directory/Phone_Bent_01.pdf_02.pdf_03.pdf
[3] => directory/Phone_Twisted_01.pdf_02.pdf_03.pdf
[4] => directory/Phone_Cracked_01.pdf_02.pdf_03.pdf
[5] => directory/Phone_Scratched_01.pdf_02.pdf_03.pdf
[6] => directory/Phone_Bent_01.pdf_02.pdf_03.pdf
[7] => directory/Phone_Twisted_01.pdf_02.pdf_03.pdf
[8] => directory/Phone_Cracked_01.pdf_02.pdf_03.pdf
[9] => directory/Phone_Scratched_01.pdf_02.pdf_03.pdf
[10] => directory/Phone_Bent_01.pdf_02.pdf_03.pdf
[11] => directory/Phone_Twisted_01.pdf_02.pdf_03.pdf
)
And want to make this...
Array (
[0] => directory/Phone_Cracked_01.pdf
[1] => directory/Phone_Cracked_02.pdf
[2] => directory/Phone_Cracked_03.pdf
[3] => directory/Phone_Scratched_01.pdf
[4] => directory/Phone_Scratched_02.pdf
[5] => directory/Phone_Scratched_03.pdf
[6] => directory/Phone_Bent_01.pdf
[7] => directory/Phone_Bent_02.pdf
[8] => directory/Phone_Bent_03.pdf
[9] => directory/Phone_Twisted_01.pdf
[10] => directory/Phone_Twisted_02.pdf
[11] => directory/Phone_Twisted_03.pdf
)
for ($z=1;$z<=count($ailments_checkvar);$z++) {
$ailments_checkvar[$z-1] = $ailments_checkvar[$z-1].'_0'.$z.'.pdf';
}
unset($z);
what ever u did was causing the stack problem for $ailments_checkvar
please check out this is optimized code.
your error lies in $valueN = $ailments_checkvar.'_0'.$n.'.pdf';
Look at this statement here,
$valueN = $ailments_checkvar.'_0'.$n.'.pdf';
^^^^^^^^^^^^^^^^^^
$ailments_checkvar is an array, not a string. In the above statement, you're trying to convert an array to a string. It should be,
$valueN = $valueN.'_0'.$n.'.pdf';
Update(1):
Based on the requirement you posted above, the solution would be like this:
$equip = 'Phone';
$ailments_checkvar = explode(', ', 'Cracked, Scratched, Bent, Twisted');
$path_array = array();
foreach($ailments_checkvar as $property_status){
for($i = 1; $i <= 3; ++$i){
$path_array[] = 'directory/' . $equip . '_' . $property_status . '_0' . $i . '.pdf';
}
}
echo '<pre>'; print_r ($path_array);
Here's the live demo.

how to use round robin method in array in php?

Hi i am trying to create a sub array from an array.i.e; think I have an array such as given below
$array = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19}
which I explode and assign it to a variable $i..
and run the for loop as shown below..
for ( $i=0;$i<count($array);$i++) {
$a = array();
$b = $array[$i];
for($j=0;$j<count($array);$j++){
if($b != $array[$j]){
$a[] = $array[$j];
}
}
the output I want is when
$i = 1
the array should be
{2,3,4,5,6,7,8,9,10,11}
and when
$i = 2
the array should be
{3,4,5,6,7,8,9,10,11,12}
similarly when
$i=19
the array should be
{1,2,3,4,5,6,7,8,9,10}
so how can I do it.
Assuming $i is supposed to be an offset and not the actual value in the array, you can do
$fullArray = range(1, 19);
$i = 19;
$valuesToReturn = 10;
$subset = iterator_to_array(
new LimitIterator(
new InfiniteIterator(
new ArrayIterator($fullArray)
),
$i,
$valuesToReturn
)
);
print_r($subset);
This will give your desired output, e.g.
$i = 1 will give 2 to 11
$i = 2 will give 3 to 12
…
$i = 10 will give 11 to 1
$i = 11 will give 12 to 2
…
$i = 19 will give 1 to 10
$i = 20 will give the same as $i = 1 again
and so on.
$array = range(1, 19);
$i = 19;
$result = array();
$after = array_slice($array, $i, 10);
$before = array_slice($array, 0, 10 - count($after));
$result = array_merge($after, $before);
var_dump(json_encode($result));
P.S. please note 0 element has 1 value and so on...
for ($i = 0; $i < count($array); $i++) {
if ($i + 10 < count($array))
$a = array_slice($array, $i, 10);
else
$a = array_merge(array_slice($array, $i), array_slice($array, 0, 10-(count($array)-$i)));
// do something with $a before it is over-written on the next iteration
}
This test:
<?php
$array = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19);
for ($i = 0; $i < count($array); $i++) {
if ($i + 10 < count($array))
$a = array_slice($array, $i, 10);
else
$a = array_merge(array_slice($array, $i), array_slice($array, 0, 10-(count($array)-$i)));
echo "<h2>$i</h2>\n<pre>".print_r($a,true)."</pre><br />\n";
}
Resulted in this:
0
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
)
...
9
Array
(
[0] => 10
[1] => 11
[2] => 12
[3] => 13
[4] => 14
[5] => 15
[6] => 16
[7] => 17
[8] => 18
[9] => 19
)
10
Array
(
[0] => 11
[1] => 12
[2] => 13
[3] => 14
[4] => 15
[5] => 16
[6] => 17
[7] => 18
[8] => 19
[9] => 1
)
...
18
Array
(
[0] => 19
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
[7] => 7
[8] => 8
[9] => 9
)
This works fine from my end
<?php
$array = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19);
$size = sizeof($array); // Defining the array size
$str = 17; // This is the reference value from which you have to extract the values
$key = array_search($str, $array);
$key = $key+1; // in order to skip the given reference value
$start = $key%$size;
$end = $start+9;
for($i=$start; $i<=$end; $i++) {
$j = ($i%$size);
$result[] = $array[$j];
}
echo '<pre>'; print_r($result);
?>
It looks like all you need is a slice of a certain size from the array, slice that wraps around the array's end and continues from the beginning. It treats the array like a circular list.
You can achieve this in many ways, one of the simplest (in terms of lines of code) is to extend the original array by appending a copy of it at its end and use the PHP function array_slice() to extract the slice you need:
function getWrappedSlice(array $array, $start, $count = 10)
{
return array_slice(array_merge($array, $array), $start, $count);
}
Of course, you have to be sure that $start is between 0 and count($array) - 1 (including), otherwise the value returned by the function won't be what you expect.
Round-robin on an array can be achieved by doing a "rotate" operation inside each iteration:
for ($i = 0; $i < count($array); ++$i) {
// rotate the array (left)
array_push($array, array_shift($array));
// use $array
}
During the loop, the first element of the array is placed at the back. At the end of the loop, the array is restored to its original value.

Simple array operation in PHP

Let's say I have following array:
Array
(
[0] => Array
(
[0] => a
[1] => 1
)
[1] => Array
(
[0] => b
[1] => 8
)
[2] => Array
(
[0] => c
[1] => 16
)
[3] => Array
(
[0] => d
[1] => 21
)
....
)
Numbers in inner array are generated randomly from range (0, 100) and they don't repeat.
I would like to create a loop, which will iterate from 0 to 100 and check if loop iteration is equal to inner number of above array. Excepted result is array with 100 elements:
Array
(
[0] => const
[1] => a
[2] => const
[3] => const
[4] => const
[5] => const
[6] => const
[7] => const
[8] => b
[9] => const
[10] => const
.
.
[16] => c
[17] => const
.
.
[21] => d
[22] => const
[23] => const
.
.
)
What I need is something like:
for ($i=0; $i < 100; $i++) {
if($i === $name[$i][1]) {
$new_array[] = $name[$i][0];
} else {
$new_array[] = 'const';
}
}
But I can't get it working, thus I need some help.
I am not an English native speaker, so hopefully you understand what I would like to achieve. Thanks for any help.
you need a nested loop like:
for ($i=0; $i < 100; $i++):
$found = false;
foreach($name as $array):
if($array[1] === $i):
$found = true;
$new_array[] = $array[0];
endif;
endforeach;
if(!$found):
$new_array[] = 'const';
endif;
endfor;
The reason it doesn't work is because each time $i is incremented you're trying to make a match in $name[$i], and not checking all of the arrays in $name, the simplest solution I can think of (and to perform the least number of iterations) would be to do something like:
$new_array = array();
foreach ($name as $n) {
$new_array[$n[1]] = $n[0];
}
for ($i=0; $i<100; $i++) {
if (!isset($new_array[$i])) {
$new_array[$i] = 'const';
}
}
ksort($new_array);
So first of all, loop through your $name array, and set up your $new_array with the the key => value pair (eg. [1] => 'a', [8] => 'b'), then in the for loop just check if the key ($i) has already been set, and if not, set it with the value 'const'. Finally, sort the $new_array by its keys.
The number of iterations in this example is count($name) + 100, whereas a nested loop for example would be 100 * count($name).
use
for ($i=0; $i < 100; $i++) {
if($i === $name[$i][1]) {
$new_array[$i] = $name[$i][0];
}
else{
$new_array[$i] = 'const';
}
}
for ($i = 0; $i < count($name); ++$i) {
if ($name[$i][1] === $i) {
$name[$i] = $name[$i][0];
} else {
$name[$i] = 'const';
}
}
Why do u use Identical operator instead of Equal
for ($i=0; $i < 100; $i++) {
if($i == $name[$i][1]) {
$new_array[] = $name[$i][0];
} else {
$new_array[] = 'const';
}
}

Categories