If I had an array like this...
array('1','2','3','4','10')
... how could I remove elements before the element whose value I supply.
For example:
If I supplied 1 then array = (1,2,3,4,10)
If it were 2 then array = (2,3,4,10) //Remove the numbers before 2
If it were 3 then array = (3,4,10) //Remove the numbers before 3
If it were 4 then array = (4,10) //Remove the numbers before 4
If it were 10 then array = (10) //Remove all before the 10
I'm currently thinking of doing with using if else. But is there a way to do this using some kind of php array function itself.
Make use of array_search and array_slice
<?php
$arr=array_slice($arr, array_search('4',array('1','2','3','4','10')));
print_r($arr);
OUTPUT :
Array
(
[0] => 4
[1] => 10
)
Demo
Maybe this would help:
$myArray = array('1','2','3','4','10');
$x=3;
$myArray = array_splice($myArray, array_search($x, $myArray), count($myArray));
$myArray = array('1','2','3','4','10');
$value = 3;
$key = array_search($value, $myArray);
$myNewArray = array_splice($myArray, 0, $key);
$array = array_filter($array, function($item) use ($filterItem) {
return $item !== $filterItem;
});
Will filter out every item equal to $filterItem. array_filter on php.net
Related
I am reading value from CMD which is running a python program and my output as follows:
Let as assume those values as $A:
$A = [[1][2][3][4]....]
I want to make an array from that as:
$A = [1,2,3,4....]
I had tried as follows:
$val = str_replace("[","",$A);
$val = str_replace("]","",$val);
print_r($val);
I am getting output as:
Array ( [0] => 1 2 3 4 ... )
Please guide me
try this
// your code goes here
$array = array(
array("1"),
array("2"),
array("3"),
array("4")
);
$outputArray = array();
foreach($array as $key => $value)
{
$outputArray[] = $value[0];
}
print_r($outputArray);
Also check the example here https://ideone.com/qaxhGZ
This will work
array_reduce($a, 'array_merge', array());
Multidimensional array to single dimensional array,
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($A));
$A = iterator_to_array($it, false);
But, if $A is string
$A = '[[1][2][3][4]]';
$A = explode('][', $A);
$A = array_map(function($val){
return trim($val,'[]');
}, $A);
Both codes will get,
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
This function will work when you do indeed have a multidimensional array, which you stated you have, in stead of the String representation of a multidimensional array, which you seem to have.
function TwoDToOneDArray($TwoDArray) {
$result = array();
foreach ($TwoDArray as $value) {
array_push($result, $value[0]);
}
return $result;
}
var_dump(TwoDToOneDArray([[0],[1]]));
You can transform $A = [[1],[2],[3],[4]] into $B = [1,2,3,4....] using this following one line solution:
$B = array_map('array_shift', $A);
PD: You could not handle an array of arrays ( a matrix ) the way you did. That way is only for managing strings. And your notation was wrong. An array of arrays (a matrix) is declared with commas.
If you have a string like you wrote in the first place you can try with regex:
$a = '[[1][2][3][4]]';
preg_match_all('/\[([0-9\.]*)\]/', $a, $matches);
$a = $matches[1];
var_dump($a);
If $A is a string that looks like an array, here's one way to get it:
$A = '[[1][2][3][4]]';
print "[".str_replace(array("[","]"),array("",","),substr($A,2,strlen($A)-4))."]";
It removes [ and replaces ] with ,. I just removed the end and start brackets before the replacement and added both of them after it finishes. This outputs: [1,2,3,4] as you can see in this link.
This question already has answers here:
php - how to remove all elements of an array after one specified
(3 answers)
Closed 9 years ago.
Is it possible to delete all array elements after an index?
$myArrayInit = array(1=>red, 30=>orange, 25=>velvet, 45=>pink);
now some "magic"
$myArray = delIndex(30, $myArrayInit);
to get
$myArray = array(1=>red, 30=>orange);
due to the keys in $myArray are not successive, I don't see a chance for array_slice()
Please note : Keys have to be preserved! + I do only know the Offset Key!!
Without making use of loops.
<?php
$myArrayInit = [1 => 'red', 30 => 'orange', 25 => 'velvet', 45 => 'pink']; //<-- Your actual array
$offsetKey = 25; //<--- The offset you need to grab
//Lets do the code....
$n = array_keys($myArrayInit); //<---- Grab all the keys of your actual array and put in another array
$count = array_search($offsetKey, $n); //<--- Returns the position of the offset from this array using search
$new_arr = array_slice($myArrayInit, 0, $count + 1, true);//<--- Slice it with the 0 index as start and position+1 as the length parameter.
print_r($new_arr);
Output :
Array
(
[1] => red
[30] => orange
[25] => velvet
)
Try
$arr = array(1=>red, 30=>orange, 25=>velvet, 45=>pink);
$pos = array_search('30', array_keys($arr));
$arr= array_slice($arr,0,$pos+1,true);
echo "<pre>";
print_r($arr);
See demo
I'd iterate over the array up until you reach the key you want to truncate the array thereafter, and add those items to a new - temporary array, then set the existing array to null, then assign the temp array to the existing array.
This uses a flag value to determine your limit:
$myArrayInit = array(1=>'red', 30=>'orange', 25=>'velvet', 45=>'pink');
$new_array = delIndex(30,$myArrayInit);
function delIndex($limit,$array){
$limit_reached=false;
foreach($array as $ind=>$val){
if($limit_reached==true){
unset($array[$ind]);
}
if($ind==$limit){
$limit_reached=true;
}
}
return $array;
}
print_r($new_array);
Try this:
function delIndex($afterIndex, $array){
$flag = false;
foreach($array as $key=>$val){
if($flag == true)
unset($array[$key]);
if($key == $afterIndex)
$flag = true;
}
return $array;
}
This code is not tested
How can I delete duplicates in array?
For example if I had the following array:
$array = array('1','1','2','3');
I want it to become
$array = array('2','3');
so I want it to delete the whole value if two of it are found
Depending on PHP version, this should work in all versions of PHP >= 4.0.6 as it doesn't require anonymous functions that require PHP >= 5.3:
function moreThanOne($val) {
return $val < 2;
}
$a1 = array('1','1','2','3');
print_r(array_keys(array_filter(array_count_values($a1), 'moreThanOne')));
DEMO (Change the PHP version in the drop-down to select the version of PHP you are using)
This works because:
array_count_values will go through the array and create an index for each value and increment it each time it encounters it again.
array_filter will take the created array and pass it through the moreThanOne function defined earlier, if it returns false, the key/value pair will be removed.
array_keys will discard the value portion of the array creating an array with the values being the keys that were defined. This final step gives you a result that removes all values that existed more than once within the original array.
You can filter them out using array_count_values():
$array = array('1','1','2','3');
$res = array_keys(array_filter(array_count_values($array), function($freq) {
return $freq == 1;
}));
The function returns an array comprising the original values and their respective frequencies; you then pick only the single frequencies. The end result is obtained by retrieving the keys.
Demo
Try this code,
<?php
$array = array('1','1','2','3');
foreach($array as $data){
$key= array_keys($array,$data);
if(count($key)>1){
foreach($key as $key2 => $data2){
unset($array[$key2]);
}
}
}
$array=array_values($array);
print_r($array);
?>
Output
Array ( [0] => 2 [1] => 3 )
PHP offers so many array functions, you just have to combine them:
$arr = array_keys(array_filter(array_count_values($arr), function($val) {
return $val === 1;
}));
Reference: array_keys, array_filter, array_count_values
DEMO
Remove duplicate values from an array.
array_unique($array)
$array = array(4, "4", "3", 4, 3, "3");
$result = array_unique($array);
print_r($result);
/*
Array
(
[0] => 4
[2] => 3
)
*/
I have two preg_match() calls and i want to merge the arrays instead of replacing the first array. my code so far:
$arr = Array();
$string1 = "Article: graphics card";
$string2 = "Price: 300 Euro";
$regex1 = "/Article[\:] (?P<article>.*)/";
$regex2 = "/Price[\:] (?P<price>[0-9]+) Euro/";
preg_match($regex1, $string1, $arr);
//output here:
$arr['article'] = "graphics card"
$arr['price'] = null
preg_match($regex2, $string2, $arr);
//output here:
$arr['article'] = null
$arr['price'] = "300"
How may I match so my output will be:
$arr['article'] = "graphics card"
$arr['price'] = "300"
?
You could use preg_replace_callback and handle the merging inside the callback function.
If it were me this is how I would do it, this would allow for easier extension at a later date, and would avoid using a callback function. It could also support searching one string easily by replacing $strs[$key] and the $strs array with a singular string var. It doesn't remove the numerical keys, but if you are only ever to go on accessing the associative keys from the array this will never cause a problem.
$strs = array();
$strs[] = "Article: graphics card";
$strs[] = "Price: 300 Euro";
$regs = array();
$regs[] = "/Article[\:] (?P<article>.*)/";
$regs[] = "/Price[\:] (?P<price>[0-9]+) Euro/";
$a = array();
foreach( $regs as $key => $reg ){
if ( preg_match($reg, $strs[$key], $b) ) {
$a += $b;
}
}
print_r($a);
/*
Array
(
[0] => Article: graphics card
[article] => graphics card
[1] => graphics card
[price] => 300
)
*/
You can use array_merge for this if you store your results in two different arrays.
But your output depicted above is not correct. You do not have $arr['price'] if you search with regex1 in your string but only $arr['article']. Same applies for the second preg_match.
That means if you store one result in $arr and one in $arr2 you can merge them into one array.
preg_match does not offer the functionality itself.
Use different array for second preg_match ,say $arr2
Traverse $arr2 as $key => $value .
Choose non null value out of $arr[$key] and $arr2[$key], and write that value to $arr[$key].
$arr will have required merged array.
This should work for your example:
array_merge( // selfexplanatory
array_filter( preg_match($regex1, $string1, $arr)?$arr:array() ), //removes null values
array_filter( preg_match($regex2, $string2, $arr)?$arr:array() )
);
I have 2 arrays with for example 1000 key's each, one holds a temperature value and the other the hour.
Example array temp:
[0] = 3.1
[1] = 4.3
[2] = 4.1
[3] = 5.1
[4] = 4.1
Example hour array:
[0] = 0
[1] = 1
[2] = 2
[3] = 3
[4] = 3
The problem with this is that when i combine these to arrays and plot this in for example pchart i have too many values on the X and it gets cluttered.
So what i need to to remove the duplicate hours and replace then with "NULL", so that the unneeded hours are not plotted on the x axis.
I want to keep the first hour in the array, the second to the end of the duplicates can be set to "NULL"
The hour output array should be:
[0] = 0
[1] = 1
[2] = 2
[3] = 3
[4] = NULL
etc.
Sounds like a job for array_unique().
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
Takes an input array and returns a new array without duplicate values.
Note that keys are preserved. array_unique() sorts the values treated
as string at first, then will keep the first key encountered for every
value, and ignore all following keys. It does not mean that the key of
the first related value from the unsorted array will be kept.
Note: Two elements are considered equal if and only if (string) $elem1
=== (string) $elem2. In words: when the string representation is the same. The first element will be used.
If you require the array keys to persist, you can try something with array_map().
<?php
//Variable initialization
$array = array(
0 => 0,
1 => 1,
2 => 2,
3 => 3,
4 => 3
);
$temp = array();
$array = array_map(function($element) use (&$temp) {
if (!in_array($element, $temp)) {
$temp[] = $element;
return $element;
}
return null;
}, $array);
print_r($array);
Your array is sorted, so... how about this?
$hours = array(0,1,2,3,3,4,4,5);
$prev = -1;
foreach ($hours as &$hour) {
if ($prev === $hour) {
$hour = NULL;
}
else {
$prev = $hour;
}
}
unset($hour);
print_r($hours); // 0,1,2,3,NULL,4,NULL,5...
If you're using php 5.3:
$a = array(0,1,2,3,4,4,5);
array_walk($a, function(&$item) {
static $encountered = array();
if(in_array($item, $encountered)) {
$item = null;
return;
}
$encountered[] = $item;
});
var_dump($a);
Will preserve the number of keys. Array_walk calls a user function for every key. static makes it so that the $encountered array in the scope of the function stays between executions.
If you want to remove the duplicates entirely you can use array_unique()
but it wont set them to NULL.
Maybe this trick does it:
$simplified = array_combine($hours, $temperatures);
$hours = array_keys($simplified);
$temperatures = array_values($simplified);
This won't set things to NULL but to completely remove them which I think is what you're looking for. Otherwise this should do it:
foreach(array_slice(array_reverse(array_keys($hours)), 0, -1) as $i)
($hours[$i] === $hours[$i-1]) && $hours[$i] = NULL;
Demo