Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Is there any way to use substr() function on all of an array's elements without using a loop?
Looping is sometimes the most simple and readable solution. But if you want to apply a function to every element of an array you can also use array_map.
Here an anonymous function is a simple wrapper for substr, which is used to return the first letter of each name in the given array:
<?php
$names =
[
'Gaga',
'Joplin',
'Vega'
];
$first_letters =
array_map(
function($str) { return substr($str, 0, 1); },
$names
);
var_export($first_letters);
Output:
array (
0 => 'G',
1 => 'J',
2 => 'V',
)
Short arrow functions introduced in Php 7.4. are slightly tidier:
array_map(
fn($str) => substr($str, 0, 1),
$names
);
The foreach/loop approach:
foreach($names as $key => $name)
$result[$key] = substr($name, 0, 1);
Mutating the original array:
foreach($names as &$name)
$name = substr($name, 0, 1);
unset($name);
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
I have two arrays:
$array1 = array('104', '104', '104', '51', '228', '228');
$array2 = array('12121', '12120', '12119', '11821', '11788', '11787');
I need to create an array with two dimensions consisting of the elements of these two arrays in a specific way:
$array3 = array('104'=>array('12121', '12120', '12119'),'51'=>array('11821'),'228'=>array('11788', '11787'));
Array1 and Array2 always have the same number of elements.
How can I do this?
You can do it this way:
<?php
$array1 = ['104', '104', '104', '51', '228', '228'];
$array2 = ['12121', '12120', '12119', '11821', '11788', '11787'];
$result = [];
$index = 0;
foreach( $array1 as $key => $value ){
$result[$value][] = $array2[$index];
$index++;
}
Result:
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 4 years ago.
Improve this question
Im new In PHP!.
I have an array that contains dates and vlaues. How do i get all values of
specific date?. EXp: I would like to get all values from year 2015. If someone Knows can guide me.
You could use array_filter, then check the array key substr matches the date.
<?php
$date = 2016;
$array = [
'2016-01-01' => 'a',
'2016-01-02' => 'b',
'2016-12-01' => 'c',
'2017-01-04' => 'd',
'2017-01-05' => 'e',
'2017-01-06' => 'f',
];
$result = array_filter($array, function ($key) use ($date) {
return substr($key, 0, strlen($date)) == $date;
}, ARRAY_FILTER_USE_KEY);
print_r($result);
https://3v4l.org/UYaQq
Result:
Array
(
[2016-01-01] => a
[2016-01-02] => b
[2016-12-01] => c
)
<?php
$array = array('2015-01-01' => "test1",
'2013-02-04' => "test2",
'2011-03-08' => "test3",
'2016-03-08' => "test3");
foreach( $array as $key => $value ){
if(date('Y',strtotime($key)) >= 2015)
echo $value . ", ";
}
?>
An Array Contains a Key and a Value. The Key in your case is the Date. And the Value is... the value
You define it like this
$array = array(
Date => Value,
AnotherDate => AnotherValue,
);
or since PHP5
$array = [
Date => Value,
AnotherDate => AnotherValue,
];
if you now look at your Array using
var_dump($array);
You'll see the date is already combined with your value and It will even show the type of value (boolean, string, integer...)
Edit
Anotherone was faster
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have one-dimensional array, e.g.
$arr = ['foo', 'bar', 'baz'];
I want convert it as follow(var_dump output):
array (size=1)
'foo' =>
array (size=1)
'bar' =>
array (size=1)
'baz' => string '' (length=0)
I can use only loop(for and/or foreach). Recursive functions is not allowed. PHP as primary programming language.
Please, help me write code for this transformation.
$r = array('a', 'b', 'c');
$res = array();
foreach (array_reverse($r) as $i) {
$tmp = $res;
$res = array();
$res[$i] = $tmp;
}
echo '<pre>', print_r($res);
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 8 years ago.
Improve this question
This is my array
$array = array(
"13111" => "2014-06-21 19:51:00.0000000",
"23111" => "2014-06-20 19:51:00.0000000",
"12111" => "2014-06-21 19:51:00.0000000",
"23311" => "2014-06-22 19:51:00.0000000",
"13114" => "2014-06-21 19:51:00.0000000",
"23711" => "2014-06-20 19:51:00.0000000",
);
How can i get first 3 elements of my array and how can i sort by datetime? thanks
What you want is:
sort($array);
$array = array_slice($array, 0, 3);
first, the sort function will sort them lexicographically (which in this case coincides with the date) and then you slice it to get the elements you want.
EDIT
If you want to preserve the keys just use
asort($array); // "asort" instead of simple "sort"
$array = array_slice($array, 0, 3, true); // note the final "true" parameter!
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 10 months ago.
Improve this question
I have an array like this
$users = array(
[0] => array('Id' => 3, 'Name' => 'Bob'),
[1] => array('Id' => 8, 'Name' => 'Alice'),
)
and I want to pull the Ids 'up' one level so that the final array is:
$usersById = array(
[3] => array('Id' => 3, 'Name' => 'Bob'),
[8] => array('Id' => 8, 'Name' => 'Alice'),
)
The Id values are unique.
Is there a native PHP way to do this? The code I'm currently using is:
$usersById = array();
foreach ($users as $key => $value)
{
$usersById[$value['Id']] = $value;
}
This works, but is not terribly elegant.
Modern answer (requires PHP 5.5)
The new function array_column is very versatile and one of the things it can do is exactly this type of reindexing:
// second parameter is null means we 're just going to reindex the input
$usersById = array_column($users, null, 'Id');
Original answer (for earlier PHP versions)
You need to fetch the ids from the sub-arrays with array_map, then create a new array with array_combine:
$ids = array_map(function($user) { return $user['Id']; }, $users);
$users = array_combine($ids, $users);
The code above requires PHP >= 5.3 for the anonymous function syntax, but you can also do the same (albeit it will look a bit uglier) with create_function which only requires PHP >= 4.0.1:
$ids = array_map(create_function('$user', 'return $user["Id"];'), $users);
$users = array_combine($ids, $users);
See it in action.
You could use the array_reduce() function, like:
$usersById = array_reduce($users, function ($reduced, $current) {
$reduced[$current['Id']] = $current;
return $reduced;
});
However, it's no more elegant than a foreach.
I think using foreach is much more elegant. Maybe you just only want to write it differently:
$keyed = array();
foreach($users as $w) $keyed[$w['Id']] = $w;
In case you want to replace the existing array, foreach is not that flexible indeed. But maybe the following is some sort of alternative:
$users = function($key) use ($users)
{
foreach($users as $v) $keys[] = $v[$key];
return array_combine($keys, $users);
};
$users = $users('Id');
It allows the callback to accept parameters, e.g. the name of the key which should be used to create the new keys from.
And one more variant using array_walk:
$usersById = array();
array_walk($users, function($val) use (&$usersById) {
$usersById[$val['Id']] = $val;
});