I have this kind of simple array:
$puctures=array('1_noname.jpg','2_new.jpg','1_ok.jpg','3_lets.jpg','1_stack.jpg','1_predlog.jpg','3_loli.jpg');
I want to make new array that i will only have elements thats starts with 1_
Example
$new=array('1_noname.jpg','1_ok.jpg','1_stack.jpg','1_predlog.jpg');
Something like array_pop but how?
See array_filter():
$new = array_filter(
$puctures,
function($a) {return substr($a, 0, 2) == '1_'; }
);
A simple loop will do.
foreach ($pictures as $picture) {
if (substr($picture, 0, 2) == "1_") {
$new[] = $picture;
}
}
Use array_filter() to get your array:
$new = array_filter($puctures, function($item)
{
//here strpos() may be a better option:
return preg_match('/^1_/', $item);
});
This examples uses array_push() & strpos()
$FirstPictures = array();
foreach( $pictures as $pic => $value ) {
if ( strpos( $value, '1_' ) !== 0 ) {
array_push( $FirstPictures, $pic );
}
}
$puctures=array('1_noname.jpg','2_new.jpg','1_ok.jpg','3_lets.jpg','1_stack.jpg','1_predlog.jpg','3_loli.jpg');
$new=array();
foreach($puctures as $value)
{
if(strchr($value,'1'))
$new[]=$value;
}
echo "<pre>"; print_r($new);
Related
This is my array:
['apple']['some code']
['beta']['other code']
['cat']['other code 2 ']
how can I replace all the "e" letters with "!" in the key name and keep the values
so that I will get something like that
['appl!']['some code']
['b!ta']['other code']
['cat']['other code 2 ']
I found this but because I don't have the same name for all keys I can't use It
$tags = array_map(function($tag) {
return array(
'name' => $tag['name'],
'value' => $tag['url']
);
}, $tags);
I hope your array looks like this:-
Array
(
[apple] => some code
[beta] => other code
[cat] => other code 2
)
If yes then you can do it like below:-
$next_array = array();
foreach ($array as $key=>$val){
$next_array[str_replace('e','!',$key)] = $val;
}
echo "<pre/>";print_r($next_array);
output:- https://eval.in/780144
You can stick with array_map actually. It is not really practical, but as a prove of concept, this can be done like this:
$array = array_combine(
array_map(function ($key) {
return str_replace('e', '!', $key);
}, array_keys($array)),
$array
);
We use array_keys function to extract keys and feed them to array_map. Then we use array_combine to put keys back to place.
Here is working demo.
Here we are using array_walk and through out the iteration we are replacing e to ! in key and putting the key and value in a new array.
Try this code snippet here
<?php
$firstArray = array('apple'=>'some code','beta'=>'other code','cat'=>'other code 2 ');
$result=array();
array_walk($firstArray, function($value,$key) use (&$result) {
$result[str_replace("e", "!", $key)]=$value;
});
print_r($result);
If you got this :
$firstArray = array('apple'=>'some code','beta'=>'other code','cat'=>'other code 2 ');
You can try this :
$keys = array_keys($firstArray);
$outputArray = array();
$length = count($firstArray);
for($i = 0; $i < $length; $i++)
{
$key = str_replace("e", "!", $keys[ $i ]);
$outputArray[ $key ] = $firstArray[$keys[$i]];
}
We can iterate the array and mark all problematic keys to be changed. Check for the value whether it is string and if so, make sure the replacement is done if needed. If it is an array instead of a string, then call the function recursively for the inner array. When the values are resolved, do the key replacements and remove the bad keys. In your case pass "e" for $old and "!" for $new. (untested)
function replaceKeyValue(&$arr, $old, $new) {
$itemsToRemove = array();
$itemsToAdd = array();
foreach($arr as $key => $value) {
if (strpos($key, $old) !== false) {
$itemsToRemove[]=$key;
$itemsToAdd[]=str_replace($old,$new,$key);
}
if (is_string($value)) {
if (strpos($value, $old) !== false) {
$arr[$key] = str_replace($old, $new, $value);
}
} else if (is_array($value)) {
$arr[$key] = replaceKeyValue($arr[$key], $old, $new);
}
}
for ($index = 0; $index < count($itemsToRemove); $index++) {
$arr[$itemsToAdd[$index]] = $itemsToRemove[$index];
unset($arr[$itemsToRemove[$index]]);
}
return $arr;
}
Another option using just 2 lines of code:
Given:
$array
(
[apple] => some code
[beta] => other code
[cat] => other code 2
)
Do:
$replacedKeys = str_replace('e', '!', array_keys($array));
return array_combine($replacedKeys, $array);
Explanation:
str_replace can take an array and perform the replace on each entry. So..
array_keys will pull out the keys (https://www.php.net/manual/en/function.array-keys.php)
str_replace will perform the replacements (https://www.php.net/manual/en/function.str-replace.php)
array_combine will rebuild the array using the keys from the newly updated keys with the values from the original array (https://www.php.net/manual/en/function.array-combine.php)
I`m using $_POST array with results of checkbox's selected from a form.
I'm thinking of using php in_array function but how could I extract only values that start with chk Given the following array:
Array (
[chk0] => 23934567622639616
[chk3] => 23934567622639618
[chk4] => 23934567622639619
[select-all] => on
[process] => Process
)
Thanks!
Simple and fast
$result=array();
foreach($_POST as $key => $value){
if(substr($key, 0, 2) == 'chk'){
$result[$key] = $value;
}
}
Lots of ways to do this, I like array_filter.
Example:
$result = array_filter(
$_POST,
function ($key) {
return strpos($key, "chk") === 0;
},
ARRAY_FILTER_USE_KEY
);
Here's a solution from http://php.net/manual/en/function.preg-grep.php
<?php
function preg_grep_keys($pattern, $input, $flags = 0) {
return array_intersect_key($input, array_flip(preg_grep($pattern, array_keys($input), $flags)));
}
?>
I would use array_filter
$ary = array_filter($originalArray,
function($key){ return preg_match('/chk/', $key); },
ARRAY_FILTER_USE_KEY
);
I want check my array value with in_array my arrays this is:
I use this code but it's not work
if(in_array(167, $array) AND in_array(556, $array) ) {
echo 'ok';
return;
}
now how can check my values?
in_array() does not work for multi-dimensional arrays , you either have to loop it and do the in_array() check or merge the array into a single one and then do single in_array() check.
Way 1:
foreach($array as $k=>$arr)
{
if(in_array(167,$arr))
{
echo "Found";
}
}
Way 2: (Merge)
$merged_arr = call_user_func_array('array_merge', $array);
if(in_array(167,$merged_arr))
{
echo "Found";
}
EDIT :
<?php
$array = array(array(167),array(167),array(556));
$merged_arr = call_user_func_array('array_merge', $array);
$needle_array = array(167,556,223);
foreach($needle_array as $v)
{
if(in_array($v,$merged_arr))
{
echo "Found";
}
}
You can even use array_intersect() on these two arrays to get the matched content , if that is what you are looking for.
You could create a mult-dimensional in_array function:
function inArrayMulti($needle, $haystack, $strict=false) {
foreach( $haystack as $item ) {
if( is_array($item) ) return inArrayMulti($needle, $item);
else {
if( $strict && $needle === $item) ) return true;
else if( $needle == $item ) return true;
}
}
return false;
}
May be useful this
return 0 < count(
array_filter(
$my_array,
function ($a) {
return array_key_exists('id', $a) && $a['id'] == 152;
}
)
);
Or
$lookup_array=array();
foreach($my_array as $arr){
$lookup_array[$arr['id']]=1;
}
Now you can check for an existing id very fast, for example:
echo (isset($lookup_array[152]))?'yes':'no';
Loop through the array
<?php
foreach($array as $ar){
if(in_array(167,$ar) && in_array(556,$ar)){
echo "ok";
}
}
?>
Why all answers use in_array and other difficult construction? We need found only two numbers, easy way for this:
$array = array(array(165), array(167),array(167),array(556));
foreach($array as $key){
foreach($key as $next){
echo 167 == $next || 556 == $next ? '<p>Found<p></br>' : '';
}
}
I have a PHP array with a parent called "items." In that array, I want to remove all values that do not contain a string (which I'm gonna use regex to find). How would I do this?
foreach($array['items'] as $key=>$value) { // loop through the array
if( !preg_match("/your_regex/", $value) ) {
unset($array['items'][$key]);
}
}
You can try using array_filter.
$items = array(
#some values
);
$regex= '/^[some]+(regex)*$/i';
$items = array_filter($items, function($a) use ($regex){
return preg_match($regex, $a) !== 0;
});
NOTE: This only works in PHP 5.3+. In 5.2, you can do it this way:
function checkStr($a){
$regex= '/^[some]+(regex)*$/i';
return preg_match($regex, $a) !== 0;
}
$items = array(
#some values
);
$items = array_filter($items, 'checkStr');
I have an array like this :
array() {
["AG12345"]=>
array() {
}
["AG12548"]=>
array() {
}
["VP123"]=>
array() {
}
I need to keep only arrays with keys which begin with "VP"
It's possible to do it with one function ?
Yes, just use unset():
foreach ($array as $key=>$value)
{
if(substr($key,0,2)!=="VP")
{
unset($array[$key]);
}
}
From a previous question: How to delete object from array inside foreach loop?
foreach($array as $elementKey => $element) {
if(strpos($elementKey, "VP") == 0){
//delete this particular object from the $array
unset($array[$elementKey]);
}
}
This works for me:
$prefix = 'VP';
for ($i=0; $i <= count($arr); $i++) {
if (strpos($arr[$i], $prefix) !== 0)
unset($arr[$i]);
}
Another alternative (this would be way simpler if it were values instead):
array_intersect_key($arr, array_flip(preg_grep('~^VP~', array_keys($arr))));
This is only a sample how to do this, you have probably many other ways!
// sample array
$alpha = array("AG12345"=>"AG12345", "VP12548"=>"VP12548");
foreach($alpha as $val)
{
$arr2 = str_split($val, 2);
if ($arr2[0] == "VP")
$new_array = array($arr2[0]=>"your_values");
}