How to remove only item of array? [duplicate] - php

This question already has answers here:
Deleting an element from an array in PHP
(25 answers)
Closed 5 years ago.
I have an array.
$a_input = array(1,2,3,4,5)
I want to remove 1 from array . out put is :
array(2,3,4,5);
remove 2 => output:
array(1,3,4,5);
remove 3 => output :
array(1,2,4,5);
.....
how to do this with for loop ?

try this
$a_input = array(1,2,3,4,5);
$cnt=count($a_input);
for($i=0;$i<$cnt;$i++){
$remove = array($i+1);
$output1=array_diff($a_input,$remove);
var_dump("<pre>",$output1);
}
Online test

use unset.
foreach($a_input as $key => $val){
if($a_input[$key]==1) unset($a_input[$key]);
}

You can use
$array = array(1,2,3,4,5);
if (($key = array_search('1', $array)) !== false) {
unset($array[$key]);
}

Here we are searching a value in the array If it is present, then proceed to get the key at which required value is present, then unseting that value.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$a_input = array(1,2,3,4,5);
$numberToSearch=2;
if(in_array($numberToSearch,$a_input))//checking whether value is present in array or not.
{
$key=array_search($numberToSearch, $a_input);//getting the value of key.
unset($a_input[$key]);//unsetting the value
}
print_r($a_input);
Output:
Array
(
[0] => 1
[2] => 3
[3] => 4
[4] => 5
)

What you need is array_filter:
$input = array(1,2,3,4,5)
$remove = 1;
$result = array_filter($input, function ($val) use ($remove) {
return $val !== $remove;
});

You need array_diff.
$a_input = array(1,2,3,4,5);
you can create new array with values like below:
$remove = array(1,2);
$result=array_diff($a_input,$remove);
output:
array(3,4,5);
Most of the programmer use this way only.And this will work for multiple elements also.

Related

How to filter array php [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying to get the bottom values of an array with a single condition as below :
Get all numeric values until the next value is a string then stop the instruction, and leave all other values even if they are numeric
<? php $data= [1,2,3,'web',4,5,6,'web',7,8,9]; ?>
The output will be : 7,8,9
We can try first filtering to find the first non numeric entry. Then, subset the array starting with this index. Finally, filter the subset again to remove all non numeric elements.
$data= [1,2,3,'web',4,5,6,'web',7,8,9];
$sub_data = array_filter($data, function($item) { return !is_numeric($item); });
$index = array_search(current($sub_data), $data);
$sub_data = array_slice($data, $index);
$sub_data = array_filter($sub_data, function($item) { return is_numeric($item); });
print_r($sub_data);
This prints:
Array
(
[1] => 4
[2] => 5
[3] => 6
[5] => 7
[6] => 8
[7] => 9
)
i don't know if there a specific function for it but i got the same result with this
$data= [1,2,3,'web',4,5,6,'web',7,8,9];
foreach ($data as $key => $value) {
if($value=="web"){
$x =$key;
}
}
$data = array_slice($data,$x);
print_r($data);
Output:
Array ( [0] => web [1] => 7 [2] => 8 [3] => 9 )
You can use array_reverse to get values from the array with elements in reverse order.
$reversed = array_reverse($data);
and then parse the array to stop where it gets a string
foreach($reversed as $value) {
if(is_string($value)) {
break;
}
$output[] = $value;
}
//print_r($output); // to print the output array. This will return the values like 9, 8, 7
// do a reverse again to get the values in the format you want.
$final= array_reverse($output);
print_r($final); // to print the final array. This will return the values like 7, 8, 9
Here is a DEMO
You can just pop values off the end until you get to something that isn't an int.
while (is_int($n = array_pop($data))) {
$result[] = $n;
}
This will modify the data array, so if you need to keep the original values, then do this with a copy.
The test you'll want depends on whether your example data is representative and all the numeric values you want in the array are of type int, or perhaps some might be numeric strings.
$data= [1,2,3,'web',4,5,6,'web',7,8,9];
$result = [];
for($i = count($data)-1; $i >= 0; $i++) {
// If some of the values you want might be numeric strings
// (e.g. "7") or decimals (e.g. 1.5), use this
if(!is_numeric($data[$i])) {
break;
}
// If your values will only be integer type, use this
if(!is_int($data[$i])) {
break;
}
array_unshift($result,$data[$i]);
}
// If you want the results in original order
print_r($result); // Output: [7,8,9]
// If you want the results inverted
$result = array_reverse($result);
print_r($result); // Output: [9,8,7]
Try this, here i am storing values in to an array $newArray if value is integer. if string found in value just reset the array $newArray
<?php
$data = [1,2,3,'web',4,5,6,'web',7,8,9];
$newArray = array(); // resultant array
foreach ($data as $key => $value) {
if(is_int($value)){
$newArray[] = $value;
}
else{
$newArray = array(); // reset if not integer
}
}
echo "<pre>";
print_r($newArray);
?>
DEMO
Result:
Array
(
[0] => 7
[1] => 8
[2] => 9
)
Now, you can use implode() for comma separated result, like:
echo implode(",",$newArray); // 7,8,9
Edit: (08-07-2019)
If Example:
$data = [1,2,3,'web',4,5,6,'web',7,8,9,'web'];
Code:
<?php
$data = [1,2,3,'web',4,5,6,'web',7,8,9,'web'];
$newArray = array(); // resultant array
end($data);
$keyLast = key($data); // fetches the key of the element pointed to by the internal pointer
foreach ($data as $key => $value) {
if(is_int($value) ){
$newArray[] = $value;
}
else{
if($keyLast === $key) { // if last key is string overwrite the previous array.
$newArray = $newArray;
}
else{
$newArray = array(); // reset if not integer
}
}
}
echo "<pre>";
print_r($newArray);
?>
Edit:
It's better to store all integer values into an array and then use array_slice() to get let three elements from new integer array like:
<?php
$data = [1,2,3,'web',4,5,6,'web',7,8,9,'web','web','web'];
$newArray = array(); // resultant array
foreach ($data as $key => $value) {
if(is_int($value) ){
$newArray[] = $value;
}
}
$lastThreeElement = array_values(array_slice($newArray, -3, 3, true));
echo "<pre>";
print_r($lastThreeElement);
?>

How to keep only empty elements in array in php?

I have one array and i want to keep only blank values in array in php so how can i achieve that ?
My array is like
$array = array(0=>5,1=>6,2=>7,3=>'',4=>'');
so in result array
$array = array(3=>'',4=>'');
I want like this with existing keys.
You can use array_filter.
function isBlank($arrayValue): bool
{
return '' === $arrayValue;
}
$array = array(0 => 5, 1 => 6, 2 => 7, 3 => '', 4 => '');
var_dump(array_filter($array, 'isBlank'));
use for each loop like this
foreach($array as $x=>$value)
if($value=="")
{
$save=array($x=>$value)
}
if you want print then use print_r in loop
there is likely a fancy built in function but I would:
foreach($arry as $k=>$v){
if($v != ''){
unset($arry[$k]);
}
}
the problem is; you are not using an associative array so I am pretty sure the resulting values would be (from your example) $array = array(0=>'',1=>''); so you would need to:
$newArry = array();
foreach($arry as $k=>$v){
if($v == ''){
$newArry[$k] = $v;
}
}

Create groups of values from array values [duplicate]

This question already has answers here:
Finding the subsets of an array in PHP
(5 answers)
Closed 7 years ago.
I will do my best to explain this idea to you. I have an array of values, i would like to know if there is a way to create another array of combined values. So, for example:
If i have this code:
array('ec','mp','ba');
I would like to be able to output something like this:
'ec,mp', 'ec,ba', 'mp,ba', 'ec,mp,ba'
Is this possible? Ideally i don't want to have duplicate entries like 'ec,mp' and 'mp,ec' though, as they would be the same thing
You can take an arbitrary decision to always put the "lower" string first. Once you made this decision, it's just a straight-up nested loop:
$arr = array('ec','mp','ba');
$result = array();
foreach ($arr as $s1) {
foreach ($arr as $s2) {
if ($s1 < $s2) {
$result[] = array($s1, $s2);
}
}
}
You can do it as follows:
$arr = array('ec','mp','ba', 'ds', 'sd', 'ad');
$newArr = array();
foreach($arr as $key=>$val) {
if($key % 2 == 0) {
$newArr[] = $val;
} else {
$newArr[floor($key/2)] = $newArr[floor($key/2)] . ',' . $val;
}
}
print_r($newArr);
And the result is:
Array
(
[0] => ec,mp
[1] => ba,ds
[2] => sd,ad
)
Have you looked at the function implode
<?php
$array = array('ec','mp','ba');
$comma_separated = implode(",", $array);
echo $comma_separated; // ec,mp,ba
?>
You could use this as a base for your program and what you are trying to achieve.

PHP - Use everything from 1st array, remove duplicates from 2nd?

I have 2 arrays - the first one is output first in full. The 2nd one may have some values that were already used/output with the first array. I want to "clean up" the 2nd array so that I can output its data without worrying about showing duplicates. Just to be sure I have the terminology right & don't have some sort of "array within an array", this is how I access each one:
1st Array
$firstResponse = $sth->fetchAll();
foreach ($firstResponse as $firstResponseItem) {
echo $firstResponseItem['samecolumnname']; // Don't care if it's in 2nd array
}
2nd Array
while( $secondResponseRow = $dbRequest->fetch_assoc() ){
$secondResponseArray = array($secondResponseRow);
foreach ($secondResponseArray as $secondResponseItem){
echo $secondResponseItem['samecolumnname']; //This can't match anything above
}
}
Thanks!
For example:
$response_names = array();
$firstResponse = $sth->fetchAll();
foreach ($firstResponse as $firstResponseItem)
$response_names[] = $firstResponseItem['samecolumnname'];
while( $secondResponseRow = $dbRequest->fetch_assoc() ){
$secondResponseArray = array($secondResponseRow);
foreach ($secondResponseArray as $secondResponseItem) {
if (!in_array($secondResponseItem['samecolumnname'], $response_names))
$response_names[] = $secondResponseItem['samecolumnname'];
}
}
array_walk($response_names, function($value) { echo $value . '<br />' });
If I understand what you're looking to do and the arrays are in the same scope, this should work.
$secondResponseArray = array($secondResponseRow);
$secondResponseArray = array_diff($secondResponseArray, $firstResponse);
//secondResponseArray now contains only unique items
foreach ($secondResponseArray as $secondResponseItem){
echo $secondResponseItem['samecolumnname'];
}
If you know that the keys of duplicate values will be the same you could use array_diff_assoc to get the items of the first array that aren't in the other supplied arrays.
This code
<?php
$a = array('abc', 'def', 'ghi', 'adg');
$b = array('abc', 'hfs', 'toast', 'adgi');
$r = array_diff_assoc($b, $a);
print_r($a);
print_r($r);
produces the following output
[kernel#~]php so_1.php
Array
(
[0] => abc
[1] => def
[2] => ghi
[3] => adg
)
Array
(
[1] => hfs
[2] => toast
[3] => adgi
)
[kernel#~]

PHP to remove duplicated values and exactly UNIQUE from multidimensional array

I found many question and answer about this, but not match what i need.
i think it's similar/same to this question but don't know why not working for this case. So please try before judging duplicates, thank you.
array source
$avar = array(
0 => array(1,2,3,4,5,6,7,8,9),
1 => array(10,11,12,13,14,15,16,17,7,8,9,10),
23 => array(21,22,23,4,5,6,7,11,12,13,14,15,21));
desired result
$avar = array(
0 => array(1,2,3,4,5,6,7,8,9),
1 => array(10,11,12,13,14,15,16,17),
23 => array(21,22,23));
PHP script
<?php
function super_unique($array)
{
$result = array_map("unserialize", array_unique(array_map("serialize", $array)));
foreach ($result as $key => $value)
{
if ( is_array($value) )
{
$result[$key] = super_unique($value);
}
}
return $result;
}
$result = super_unique($avar);
echo "<pre>";
print_r($result);
?>
similar question with answer but not solve my case:
How to remove duplicate values from a multi-dimensional array in PHP
PHP remove duplicate values from multidimensional array
Thank you all
$seen = array();
foreach($avar as &$entry){
$entry = array_unique(array_diff($entry,$seen));
$seen = array_merge($entry,$seen);
}
unset($entry);
var_dump($avar);

Categories