I have this simple array and I'd like to know how I can stop the first 2 segments from showing.
if(preg_match_all('/<td[^>]*class="sourceNameCell">(.*?)<\/td>/si', $printable, $matches, PREG_SET_ORDER));{
foreach($matches as $match) {
$data = "$match[1]";
$array = array();
preg_match( '/src="([^"]*)"/i', $data, $array ) ;
print_r("$array[1]") ;
}
Any help would be great, Thanks!
Use array_slice:
$output = array_slice($input, 2);
Stop from showing or removing?
for removing:
$array = array();
preg_match( '/src="([^"]*)"/i', $data, $array ) ;
// The following lines will remove values from the first two indexes.
unset($array[0]);
unset($array[1]);
// This line will re-set the indexes (the above just nullifies the values...) and make a new array without the original first two slots.
$array = array_values($array);
// The following line will show the new content of the array
var_dump($array);
Hope this helps!
Use array_slice($array, 2, count($array)) or make your regexp skip the first two if possible.
You could also invoke array_shift() twice on the array. This might be more optimal since it shouldn't need to make a copy of the array.
You could use array_splice to remove elements from array.
array_splice — Remove a portion of the array and replace it with something else
Elements are removed from original array and returned
$input = array("red", "green", "blue", "yellow", "black");
$part = array_splice($input, 1, 2);
var_dump($input);
var_dump($part);
See PHP fiddle
Related
if I give you:
$array = array(object1, object2, object3, object4);
and say, at position 2, remove all elements before this position so the end result is:
$array = array(object3, object4);
What would I do? I was looking at array_shift and array_splice to achieve what I wanted - how ever I am not sure which to use or how to use them to achieve the desired affect.
Use array_slice. For more detail check link http://php.net/manual/en/function.array-slice.php
$array = array(object1, object2, object3, object4);
$array = array_slice($array,2); // 2 is position
Or if you are looking into the values instead of the index, with a tiny adjustment in #Ashwani's answer you can have:
$array = array('object1', 'object2', 'object3', 'object4');
$slice = array_slice($array, array_search('object3',$array));
array_slice is one way to go about it, however, if you are wanting to remove all the elements in an any array before a specific value, without searching, then:
//assuming you've already verified the match is in the array
//make a copy of $array first if you don't want to break the original
while($array[0] !== $match) {
array_shift(&$array);
}
Alternatively, you could:
$index = array_search($match, array_values($array));
if($index !== false) $array = array_slice($array, $index);
This accomplished both the verification and slice. Note the array_values() is used to account for associative arrays.
I have an array that looks like:
Array ( [2.5] => ABDE [4.8] => Some other value )
How would I find any key/value pair where the key matches a pattern? I will know the value of the first digit in the key,but not the second. so for example, using a prefix of "2.", I want to somehow be able to find the key "2.5" and return both the key and the value "ABDE".
I was thinking about using a regular expression with a pattern like:
$prefix = 2;
$pattern = '/'.$prefix.'\.\d/i';
and then looping through the array and checking each key. (by the way, just for demo purposes, $prefix has been hardcoded to 2, but in the real system, this is a value provided by the user's input).
I'm wondering if there's a simpler way to do this?
Thanks.
I think you need something like this:
$keys = array_keys($array);
$result = preg_grep($pattern, $keys);
The result will be a array that holds all the keys that match the regex. The keys can be used to retrieve the corresponding value.
Have a look at the preg_grep function.
you can simply loop through the array and check the keys
$array = array(...your values...);
foreach($array as $key => $value) {
if (preg_match($pattern,$key)){
// it matches
}
}
You can wrap it in a function and pass your pattern as parameter
Old question, but here's what I like to do:
$array = [ '2.5' => 'ABDE', '4.8' => 'Some other value' ];
preg_grep + array_keys will find all keys
$keys = preg_grep( '/^2\.\d/i', array_keys( $array ) );
You can add array_intersect_key and array_flip to extract a slice of the array that matches the pattern
$vals = array_intersect_key( $array, array_flip( preg_grep( '/^2\.\d/i', array_keys( $array ) ) ) );
For future programmers who encounter the same issue. Here is a more complete solution which doesn't use any loops.
$array = ['2.5'=> 'ABCDE', '2.9'=>'QWERTY'];
$keys = array_keys($array);
$matchingKeys = preg_grep('/^2\.+/', $keys);
$filteredArray = array_intersect_key($array, array_flip($matchingKeys));
print_r($filteredArray);
That are my ways
$data = ["path"=>"folder","filename"=>"folder/file.txt","required"=>false];
// FIRST WAY
$keys = array_keys($data);
if (!in_array("path", $keys) && !in_array("filename",$keys) && !in_array("required",$keys)) {
return myReturn(false, "Dados pendentes");
}
// SECOND WAY
$keys = implode("," array_keys($data));
if (!preg_match('/(path)|(filename)|(required)/'), $keys) {
return myReturn(false, "Dados pendentes");
}
To get just the part of the array with matching keys you could also write
$matching_array = array_flip(preg_grep($pattern, array_flip($your_array)));
This might just lead to problems performance-wise, if your array gets too big.
There's T-Regx library for regular expression in PHP, and it kas preg::grep_keys() method.
<?php
$array = [2.5 => 'ABDE', 4.8 => 'Some other value'];
preg::grep_keys("/$prefix\.\d/i", $array);
I am looping through an array which itself contains array to find indexes of values 5 & 6.
Upon finding these indexes, I push the matched array, using array_push, into a another array. My application depends on maintaining the array indexes but array_push resets the keys to 0, 1, 2 etc rather than the matched 5, 6, 7 etc.
Rather than calling array_push you can add element this way:
$arr[5] = array("foo", "bar");
$arr[6] = array("red", "blue");
$arr[7] = array("123", "567");
Would that do or did I miss something?
$newArray = array();
foreach( $myArrays as $myArray )
if( ($result = array_search(5, $myArray)) || ($result = array_search(6, $myArray))
$newArray[$result] = $myArray[$result];
Suppose I have this array:
$array = array('10', '20', '30.30', '40', '50');
Questions:
What is the fastest/easiest way to remove the first item from the above array?
What is the fastest/easiest way to remove the last item from the above array?
So the resulting array contains only these values:
'20'
'30.30'
'40'
Using array_slice is simplest
$newarray = array_slice($array, 1, -1);
If the input array has less than 3 elements in it, the output array will be empty.
To remove the first element, use array_shift, to remove last element, use array_pop:
<?php
$array = array('10', '20', '30.30', '40', '50');
array_shift($array);
array_pop($array);
array_pop($array); // remove the last element
array_shift($array); // remove the first element
array_slice is going to be the fastest since it's a single function call.
You use it like this:
array_slice($input, 1, -1);
Make sure that the array has at least 2 items in it before doing this, though.
Check this code:
$arry = array('10', '20', '30.30', '40', '50');
$fruit = array_shift($arry);
$fruit = array_pop($arry);
print_r($arry);
Removes the first element from the array, and returns it:
array_shift($array);
Removes the last element from the array, and returns it:
array_pop($array);
If you dont mind doing them both at the same time, you can use:
array_shift($array,1,-1));
to knock off the first and last element at the same time.
Check the array_push, array_pop and array_slice documentation :)
<?php
$array = array("khan","jan","ban","man","le");
$sizeof_array = sizeof($array);
$last_itme = $sizeof_array-1;
//$slicearray= array_slice($array,'-'.$sizeof_array,4);// THIS WILL REMOVE LAST ITME OF ARRAY
$slicearray = array_slice($array,'-'.$last_itme);//THIS WILL REMOVE FIRST ITEM OF ARRAY
foreach($slicearray as $key=>$value)
{
echo $value;
echo "<br>";
}
?>
What is the fastest and easiest way to get the last item of an array whether be indexed array , associative array or multi-dimensional array?
$myArray = array( 5, 4, 3, 2, 1 );
echo end($myArray);
prints "1"
array_pop()
It removes the element from the end of the array. If you need to keep the array in tact, you could use this and then append the value back to the end of the array. $array[] = $popped_val
try this:
$arrayname[count(arrayname)-1]
I would say array_pop In the documentation: array_pop
array_pop — Pop the element off the end of array
Lots of great answers. Consider writing a function if you're doing this more than once:
function array_top(&$array) {
$top = end($array);
reset($array); // Optional
return $top;
}
Alternatively, depending on your temper:
function array_top(&$array) {
$top = array_pop($array);
$array[] = $top; // Push top item back on top
return $top;
}
($array[] = ... is preferred to array_push(), cf. the docs.)
For an associative array:
$a= array('hi'=> 'there', 'ok'=> 'then');
list($k, $v) = array(end(array_keys($a)), end($a));
var_dump($k);
var_dump($v);
Edit: should also work for numeric index arrays