This question already has answers here:
Native function to filter array by prefix
(6 answers)
Closed 3 months ago.
I have an array like:
$array = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');
I want to UNSET the values in the array that are not prefixed with OPTM.
How should that be done?
PHP 5.5
A short approach to reach the same value
$array = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');
$filtred = array_filter($array, function($item){
return (strncmp($item, 'OPTM', 4)==0);
});
var_dump($filtred);
to make your code more dynamic and optimal you can do like this
$array = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');
$prefix = 'OPTM';
$array = array_filter($array, function($item) use($prefix){
return (strncmp($item, $prefix, strlen($prefix))==0);
});
var_dump($array);
// Don't need this if using PHP 8
if (!function_exists('str_starts_with')) {
function str_starts_with($haystack, $needle) {
return (string)$needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0;
}
}
$array = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');
for ($i = 0; $i < count($array); ++$i) {
if (!str_starts_with($array[$i], 'OPTM'))
unset($array[$i]);
}
// Optional to re-index array
$array = array_values($array);
You can use foreach/str_contains/unset like:
$array = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');
foreach($array as $key => $value){
if(!str_contains($value,'OPTM')){
unset($array[$key]);
}
}
print_r($array);
/*
Array
(
[0] => OPTM3000
[2] => OPTM3002
[5] => OPTM3004
)
*/
Reference:
foreach
str_contains
unset
Use this
$array = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');
$new_array = array_filter($array, function($v,$k) {
return strpos($v,'OPTM') !==false;
}, ARRAY_FILTER_USE_BOTH);
try this
$array = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');
$newArray = array();
foreach($array as $value) {
if ( 'OPTM' == substr($value, 0, 4) ) {
$newArray[] = $value;
}
}
Use Unset or if you don like to use unset function one possible way will be to work with array_map and array_filter:
$array = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');
$arr = array_map(function($item) {
if ( str_contains($item,'OPTM')) {
return $item;
}
}, $array);
$arr = array_filter($arr);
print_r($arr);
You can iterate the elements in your array using a regex like:
foreach($array as $element){
$pattern = "OPTM/";
if(echo preg_match($pattern, $element) == 0){
$key = array_search($element, $array);
unset($array[$key]);
}
}
OK, this works for me.
$array = array('OPTM3000', 'All-Stud','OPTM3002','MUSC1001','PATH3000', 'OPTM3004');
$allowed_prefix = 'OPTM';
foreach ( $array as $key => $text )
{
if (strpos($text, $allowed_prefix) !== 0) {
unset($array[$key]);
}
}
Related
I have two array i.e $arr1 and $arr2 where I want to find missing value of $arr1 which is not present in $arr2 without using function like array_diff(), count(), explode(), implode() etc. So, How can I do this? Please help me.
code:
<?php
$arr1 = array('2','3','4','5');
$arr2 = array('1','6','7','8');
$array = array_diff($arr1,$arr2);
print_r($arr2);
?>
First approach:-
$missingValuesArray = array();
foreach($arr1 as $arr){
if(!in_array($arr,$arr2)){
$missingValuesArray[] = $arr;
}
}
print_r($missingValuesArray);
Output:- https://3v4l.org/UBS9G
Second approach:-
$missingValuesArray = array();
foreach($arr1 as $arr){
$counter = 0;
foreach($arr2 as $ar){
if($arr != $ar){
$counter++;
}
}
if($counter == sizeof($arr2)){
$missingValuesArray[] = $arr;
}
}
print_r($missingValuesArray);
Output:- https://3v4l.org/Uu6Ob
Requirement can be achieved by :
$arr1 = array('2','3','4','5');
$arr2 = array('1','6','7','8');
$diff = array();
$diff = $arr1;
$arrayDiff = array();
foreach($arr1 AS $value) {
foreach($arr2 AS $val) {
if ($value == $val) {
$arrayDiff[] = $value;
continue;
}
}
}
foreach ($arrayDiff AS $k=>$v) {
if (($key = array_search($v, $diff)) !== false) {
unset($diff[$key]);
}
}
print_r($diff);
$arr1 = array(1,2,3);
$arr2 = array("a","b","c");
$arr3 =array("1a","2b","3c");
How can I do the following ?
print
$one = 1,a,1a
$two = 2,b,2b
$three = 3,c,3c
Use array_map() function to map through all arrays at the same time. Like this :
$array_merged = array_map(function($v1,$v2,$v3) {
return $v1 . ','. $v2 . ',' . $v3;
}, $arr1, $arr2, $arr3);
/*
Array (
[0] => "1,a,1a",
[1] => "2,b,2b",
[2] => "3,c,3c",
)
*/
You can try this:
$arr1 = array(1,2,3);
$arr2 = array("a","b","c");
$arr3 = array("1a","2b","3c");
$i = 0;
foreach ($arr1 as $key => $value) {
$newArr[] = $value.",".$arr2[$i].",".$arr3[$i];
$i++;
}
echo implode("<br/>", $newArr);
Result:
1,a,1a
2,b,2b
3,c,3c
You can also perform this by using for loop.
Try this:
$arr1 = [1,2,3];
$arr2 = ["a","b","c"];
$arr3 = ["1a","2b","3c"];
$matrix = [$arr1, $arr2, $arr3];
var_dump(transpose($matrix));
function transpose($matrix) {
return array_reduce($matrix, function($carry, $item) {
array_walk($item, function ($value, $key) use (&$carry) {
$carry[$key][] = $value;
});
return $carry;
});
}
I have an array with the following keys:
Array
{
[vegetable_image] =>
[vegetable_name] =>
[vegetable_description] =>
[fruit_image] =>
[fruit_name] =>
[fruit_description] =>
}
and I would like to split them based on the prefix (vegetable_ and fruit_), is this possible?
Currently, I'm trying out array_chunk() but how do you store them into 2 separate arrays?
[vegetables] => Array { [vegetable_image] ... }
[fruits] => Array { [fruit_image] ... }
This should work for you:
$fruits = array();
$vegetables = array();
foreach($array as $k => $v) {
if(strpos($k,'fruit_') !== false)
$fruits[$k] = $v;
elseif(strpos($k,'vegetable_') !== false)
$vegetables[$k] = $v;
}
As an example see: http://ideone.com/uNi54B
Out of the Box
function splittArray($base_array, $to_split, $delimiter='_') {
$out = array();
foreach($to_split as $key) {
$search = $key.delimiter;
foreach($base_array as $ok=>$val) {
if(strpos($ok,$search)!==false) {
$out[$key][$ok] = $val;
}
}
return $out;
}
$new_array = splittArray($array,array('fruit','vegetable'));
It is possible with array_reduce()
$array = ['foo_bar' => 1, 'foo_baz' => 2, 'bar_fee' => 6, 'bar_feo' => 9, 'baz_bee' => 7];
$delimiter = '_';
$result = array_reduce(array_keys($array), function ($current, $key) use ($delimiter) {
$splitKey = explode($delimiter, $key);
$current[$splitKey[0]][] = $key;
return $current;
}, []);
Check the fiddle
Only one thins remains: you are using different forms (like "vegetable_*" -> "vegetables"). PHP is not smart enough to substitute language (that would be English language in this case) transformations like that. But if you like, you may create array of valid forms for that.
Use explode()
$arrVeg = array();
$arrFruit = array();
$finalArr = array();
foreach($array as $k => $v){
$explK = explode('_',$k);
if($explK[0] == 'vegetable'){
$arrVeg[$k] = $v;
} elseif($explK[0] == 'fruit') {
$arrFruit[$k] = $v;
}
}
$finalArr['vegetables'] = $arrVeg;
$finalArr['fruits'] = $arrFruit;
Use simple PHP array traversing and substr() function.
<?php
$arr = array();
$arr['vegetable_image'] = 'vegetable_image';
$arr['vegetable_name'] = 'vegetable_name';
$arr['vegetable_description'] = 'vegetable_description';
$arr['fruit_image'] = 'fruit_image';
$arr['fruit_name'] = 'fruit_name';
$arr['fruit_description'] = 'fruit_description';
$fruits = array();
$vegetables = array();
foreach ($arr as $k => $v) {
if (substr($k, 0, 10) == 'vegetable_') {
$vagetables[$k] = $v;
}
else if (substr($k, 0, 6) == 'fruit_') {
$fruits[$k] = $v;
}
}
print_r($fruits);
print_r($vagetables);
Working Example
I have 2D array and want to get all values which are at same index say at index '1'. what is the best way to get that as a new array.
Example: we have array(array(1,2,3), array(5,6,7)), the result must be array(2, 6).
Thanks
A simple function would do the trick:
function foobar($array, $index) {
$result = array();
foreach($array as $subarray) {
if(isset($subarray[$index])) {
$result[] = $subarray[$index];
}
}
return $result;
}
Or you can just use array_map (requires PHP 5.3):
array_map(function($array) { return $array[1]; }, $input);
$sample = array(array(1,2,3),
array(4,5,6),
array(7,8,9)
);
$index = 1;
$result = array_map(function($value) use($index) { return $value[$index]; }, $sample);
var_dump($result);
$input = array(
array(1,2,3),
array(5,6,7)
);
$output = array();
foreach ( $input as $data ) {
$output[] = $data[1];
}
$myarray=array(array(1,2,3), array(5,6,7));
$index=1;
$result=array();
foreach($myarray as $a) $result[]=$a[$index];
print_r($result);
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
From the above array i need the value Dog alone. how can i get the unique value from an array?. is there any functions in php?...
Thanks
Ravi
Have a look at:
http://php.net/function.array-unique
and maybe:
http://php.net/function.array-count-values
$a = array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
$counted = array_count_values($a);
$result = array();
foreach($counted as $key => $value) {
if($value === 1) {
$result[] = $key;
}
}
//$result is now an array of only the unique values of $a
print_r($result);
function getArrayItemByValue($search, $array) {
// without any validation and cheking, plain and simple
foreach($array as $key => $value) {
if($search === $value) {
return $key;
}
}
return false;
}
then try using it:
echo $a[getArrayitembyValue('Dog', $a)];
Try with:
$a = array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
$aFlip = array_flip($a);
$unique = array();
foreach ( array_count_values( $a ) as $key => $count ) {
if ( $count > 1 ) continue;
// $unique[ array_search($key) ] = $key;
$unique[ $aFlip[$key] ] = $key;
}
Use following function seems to be working & handy.
<?php
$array1 = array('foo', 'bar', 'xyzzy', 'xyzzy', 'xyzzy');
$dup = array_unique(array_diff_assoc($array1, array_unique($array1)));
$result = array_diff($array1, $dup);
print_r($result);
?>
You can see its working here - http://codepad.org/Uu21y6jf
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
$result = array_unique(a);
print_r($result);
try this one...