This seems so easy but i cant figure it out
$users_emails = array(
'Spence' => 'spence#someplace.com',
'Matt' => 'matt#someplace.com',
'Marc' => 'marc#someplace.com',
'Adam' => 'adam#someplace.com',
'Paul' => 'paul#someplace.com');
I need to get the next element in the array but i cant figure it out... so for example
If i have
$users_emails['Spence']
I need to return matt#someplace.com and if Its
$users_emails['Paul']
i need start from the top and return spence#someplace.com
i tried this
$next_user = (next($users_emails["Spence"]));
and this also
($users_emails["Spence"] + 1 ) % count( $users_emails )
but they dont return what i am expecting
reset($array);
while (list($key, $value) = each($array)) { ...
Reset() rewind the array pointer to the first element, each() returns the current element key and value as an array then move to the next element.
list($key, $value) = each($array);
// is the same thing as
$key = key($array); // get the current key
$value = current($array); // get the current value
next($array); // move the internal pointer to the next element
To navigate you can use next($array), prev($array), reset($array), end($array), while the data is read using current($array) and/or key($array).
Or you can use foreach if you loop over all of them
foreach ($array as $key => $value) { ...
You could do something like this:
$users_emails = array(
'Spence' => 'spence#someplace.com',
'Matt' => 'matt#someplace.com',
'Marc' => 'marc#someplace.com',
'Adam' => 'adam#someplace.com',
'Paul' => 'paul#someplace.com');
$current = 'Spence';
$keys = array_keys($users_emails);
$ordinal = (array_search($current,$keys)+1)%count($keys);
$next = $keys[$ordinal];
print_r($users_emails[$next]);
However I think you might have an error in your logic and what you are doing can be done better, such as using a foreach loop.
You would be better storing these in an indexed array to achieve the functionality you're looking for
Related
Hello guys, and Happy new year!
How can I add keys to this array
$my_array = array( [0] => 703683 [1] => 734972 [2] => 967385 )
So I would like to add a single key to all values example:
$copy_array = array( ['id'] => 703683 ['id'] => 734972 ['id'] => 967385 )
I tried this solution:
new_arr = [];
foreach ($my_array as $key => $value) {
// code..
$new_arr['id'] = $value ;
}
Output:
( [id] => 703683 )
You can't. An array key is identifying the element it represents. If you set 'id' to be a specific value, then you set it to be another specific value, then you override the former with the latter. Having separate values as ids is self-contradictory anyway, unless they identify different objects. If that's the case, then you can change your code to
new_arr = [];
foreach ($my_array as $key => $value) {
// code..
$new_arr[] = ['id' => $value] ;
}
or even
new_arr = [];
foreach ($my_array as $key => $value) {
// code..
$new_arr[$value] = ['id' => $value] ;
}
but the only use of such a change would be if they have other attributes, which are not included in the codes above, since your question does not provide any specific information about them if they exist at all. If everything is only an id, then you might as well leave it with numeric indexes.
Consider the following array:
$array[23] = array(
[0] => 'FOO'
[1] => 'BAR'
[2] => 'BAZ'
);
Whenever I want to work with the inner array, I do something like this:
foreach ($array as $key => $values) {
foreach ($values as $value) {
echo $value;
}
}
The outer foreach-loop is there to split the $key and $value-pairs of $array. This works fine for arrays with many keys ([23], [24], ...)but seems redundant if you know beforehand that $array only has one key (23 in this case). In a case as such, isn't there a better way to split the key from the values? Something like
split($array into $key => $values)
foreach ($values as $value) {
echo $value;
}
I hope I made myself clear.
reset returns the first element of you array and key returns its key:
$your_inner_arr = reset($array);
$your_key = key($array);
Yea, just get rid of your first foreach and define the array you're using with the known $key of your outter array.
foreach ($array[23] as $key =>$val):
//do whatever you want in here
endforeach;
If an array has only one element, you can get it with reset:
$ar = array(23 => array('foo', 'bar'));
$firstElement = reset($ar);
A very succinct approach would be
foreach(array_shift($array) as $item) {
echo $item;
}
I am trying to unset a group of array keys that have the same prefix. I can't seem to get this to work.
foreach ($array as $key => $value) {
unset($array['prefix_' . $key]);
}
How can I get unset to see ['prefix_' . $key] as the actual variable? Thanks
UPDATE: The $array keys will have two keys with the same name. Just one will have the prefix and there are about 5 keys with prefixed keys:
Array {
[name] => name
[prefix_name] => other name
}
I don't want to remove [name] just [prefix_name] from the array.
This works:
$array = array(
'aa' => 'other value aa',
'prefix_aa' => 'value aa',
'bb' => 'other value bb',
'prefix_bb' => 'value bb'
);
$prefix = 'prefix_';
foreach ($array as $key => $value) {
if (substr($key, 0, strlen($prefix)) == $prefix) {
unset($array[$key]);
}
}
If you copy/paste this code at a site like http://writecodeonline.com/php/, you can see for yourself that it works.
You can't use a foreach because it's only a copy of the collection. You'd need to use a for or grab the keys separately and separate your processing from the array you want to manipulate. Something like:
foreach (array_keys($array) as $keyName){
if (strncmp($keyName,'prefix_',7) === 0){
unset($array[$keyName]);
}
}
You're also already iterating over the collection getting every key. Unless you had:
$array = array(
'foo' => 1,
'prefix_foo' => 1
);
(Where every key also has a matching key with "prefix_" in front of it) you'll run in to trouble.
I'm not sure I understand your question, but if you are trying to unset all the keys with a specific prefix, you can iterate through the array and just unset the ones that match the prefix.
Something like:
<?php
foreach ($array as $key => $value) { // loop through keys
if (preg_match('/^prefix_/', $key)) { // if the key stars with 'prefix_'
unset($array[$key]); // unset it
}
}
You're looping over the array keys already, so if you've got
$array = (
'prefix_a' => 'b',
'prefix_c' => 'd'
etc...
)
Then $keys will be prefix_a, prefix_c, etc... What you're doing is generating an entirely NEW key, which'd be prefix_prefix_a, prefix_prefix_c, etc...
Unless you're doing something more complicated, you could just replace the whole loop with
$array = array();
I believe this should work:
foreach ($array as $key => $value) {
unset($array['prefix_' . str_replace('prefix_', '', $key]);
}
I have an array $data
fruit => apple,
seat => sofa,
etc. I want to loop through so that each key becomes type_key[0]['value'] so eg
type_fruit[0]['value'] => apple,
type_seat[0]['value'] => sofa,
and what I thought would do this, namely
foreach ($data as $key => $value)
{
# Create a new, renamed, key.
$array[str_replace("/(.+)/", "type_$1[0]['value']", $key)] = $value;
# Destroy the old key/value pair
unset($array[$key]);
}
print_r($array);
Doesn't work. How can I make it work?
Also, I want everything to be in the keys (not the values) to be lowercase: is there an easy way of doing this too? Thanks.
Do you mean you want to make the keys into separate arrays? Or did you mean to just change the keys in the same array?
$array = array();
foreach ($data as $key => $value)
{
$array['type_' . strtolower($key)] = array(array('value' => $value));
}
if you want your keys to be separate variables, then do this:
extract($array);
Now you will have $type_fruit and $type_sofa. You can find your values as $type_fruit[0]['value'], since we put an extra nested array in there.
Your requirements sound... suspect. Perhaps you meant something like the following:
$arr = array('fruit' => 'apple', 'seat' => 'sofa');
$newarr = array();
foreach ($arr as $key => $value)
{
$newkey = strtolower("type_$key");
$newarr[$newkey] = array(array('value' => $value));
}
var_dump($newarr);
First I wouldn't alter the input-array but create a new one unless you're in serious, serious trouble with your memory limit.
And then you can't simply replace the key to add a deeper nested level to an array.
$x[ 'abc[def]' ] is still only referencing a top-level element, since abc[def] is parsed as one string, but you want $x['abc']['def'].
$data = array(
'fruit' => 'apple',
'seat' => 'sofa'
);
$result = array();
foreach($data as $key=>$value) {
$target = 'type_'.$key;
// this might be superfluous, but who knows... if you want to process more than one array this might be an issue.
if ( !isset($result[$target]) || !is_array($result[$target]) ) {
$result[$target] = array();
}
$result[$target][] = array('value'=>$value);
}
var_dump($result);
for starters
$array[str_replace("/(.+)/", "type_$1[0]['value']", $key)] = $value;
should be
$array[str_replace("/(.+)/", type_$1[0]['value'], $key)] = $value;
I'm trying to add an extra class tag if an element / value is the first one found in an array. The problem is, I don't really know what the key will be...
A minified example of the array
Array (
[0] => Array(
id => 1
name = Miller
)
[1] => Array(
id => 4
name = Miller
)
[2] => Array(
id => 2
name => Smith
[3] => Array(
id => 7
name => Jones
)
[4] => Array(
id => 9
name => Smith
)
)
So, if it's the first instance of "name", then I want to add a class.
I think I sort of understand what you're trying to do. You could loop through the array and check each name. Keep the names you've already created a class for in a separate array.
for each element in this array
if is in array 'done already' then: continue
else:
create the new class
add name to the 'done already' array
Sorry for the pseudo-code, but it explains it fairly well.
Edit: here's the code for it...
$done = array();
foreach ($array as $item) {
if (in_array($item['name'], $done)) continue;
// It's the first, do something
$done[] = $item['name'];
}
I assume you're looping through this array. So, a simple condition can be used:
$first = 0;
foreach ($arr as $value) {
if (!$first++) echo "first class!";
echo $value;
// The rest of process.
}
To get just the first value of an array, you can also use the old fashioned reset() and current() functions:
reset($arr);
$first = current($arr);
Animuson has it good. There a small addition if I might:
> $done = array();
> foreach ($array as $item) {
> if (in_array($item['name'], $done)) continue;
> // It's the first, do something
> $done[] = $item['name']; }
the in_array() will get slow very fast. Try something like:
$done = array();
foreach ($array as $item) {
$key = $item['name'];
if( !isset( $done[$key] )) {
...
}
$done[$key] = true;
}
btw. Too bad this site doesn't support comments for all users.