This is only for arrays with index number. For example i have this arrays;
$array = [
"0" => "number 1",
"1" => "number 2",
"2" => "number 3",
"3" => "number 4",
"4" => "number 5",
"5" => "number 6",
"6" => "number 7",
"7" => "number 8",
"8" => "number 9"
];
I want to skip the loop from certain range of key indexes for example, skip the foreach if the number of index is from range 0 to 5. That means we can do just like this.
foreach($array as $key => $value){
if(array_key_exist($key, range(0,5))
continue;
echo $value."<br/>"
}
or we can using for... loop
for($ind = 0; $ind < count($array); $ind++){
if(array_key_exist($ind, range(0,5))
continue;
echo $arr[$ind]."<br/>"
}
How could i skip the index without using continue or searching the array_key first ? sure the code above looks fine to me, but if i have a bunch of arrays keys and values, i think this is not a good choice.
You can use array_diff as:
$wantKeys = array_diff(array_keys($array), range(1,5));
Now all you need is loop on the $wantKeys as:
foreach($wantKeys as $k)
echo $array[$k]; // only wanted values
The same idea can be achieve by array_diff_keys:
$wantKeys = array_diff_key($array, array_flip(range(1,5)));
You can get the slice of array from 5th index to rest,
$result = array_slice($array,5,count($array)-5, true);
array_slice — Extract a slice of the array
Note:
array_slice() will reorder and reset the integer array indices by
default. This behaviour can be changed by setting preserve_keys to
TRUE. String keys are always preserved, regardless of this parameter.
Demo.
Related
I have the following arrays:
$excel_arr = array(
["C1", "Title 3"],
["A1", "Title 1"],
["B1", "Title 2"],
["D1", "Title 4"]
);
$db_result = array(
"title_2" => "Cell 2 Value",
"title_1" => "Cell 1 Value",
"title_3" => "Cell 3 Value",
"title_5" => "Cell 5 Value"
);
$excel_db_relation = array(
"title_1" => "Title 1",
"title_2" => "Title 2",
"title_3" => "Title 3",
"title_4" => "Title 4",
"title_5" => "Title 5"
);
usort($excel_arr, function ($a, $b) { return strnatcmp($a[0], $b[0]); });
$excel_arr is an array with the titles for each column in an excel file. The first cell defines the cell coordinate and the second the actual cell value.
$db_result is an array containing queried values from a database. The key is column name in the table.
$excel_db_relation is an array which defines the relation between the 2 former arrays. Which excel column is linked to which db table column. In this example they are very similar, but in practice there might be more than just an underscore that differs.
The cell coordinates in $excel_arr defines the order in which each value must be printed. To do this I sort the array with the usort() as seen above.
I need to somehow merge these arrays so that the resulting array becomes:
array("Title 1" => "Cell 1 Value", "Title 2" => "Cell 2 Value", "Title 3" => "Cell 3 Value")
The database array didn't return a value for cell 4 and the excel sheet doesn't define a E5 cell. So these must not be included in the resulting array.
I have tried array_merge($excel_db_relation, $db_result) and various combinations of array_merge() and array_flip() but no matter what I do I can't seem to merge the arrays with "Title X" being the key.
The solution using array_intersect_key, array_intersect and array_column functions:
$result = [];
// getting concurrent 'titles'(by key)
$titles = array_intersect_key($excel_db_relation, $db_result);
foreach (array_intersect($titles, array_column($excel_arr, 1)) as $k => $v) {
$result[$v] = $db_result[$k];
}
print_r($result);
The output:
Array
(
[Title 1] => Cell 1 Value
[Title 2] => Cell 2 Value
[Title 3] => Cell 3 Value
)
Update:
Alternative approach to hold the order in which each value must be printed. Used functions: array_merge_recursive(to combine cell titles and values into separate groups) and array_column functions:
$result = [];
$bindings = array_column(array_merge_recursive($db_result, $excel_db_relation), 0, 1);
foreach (array_column($excel_arr, 1) as $title) {
if (isset($bindings[$title])) $result[$title] = $bindings[$title];
}
print_r($result);
The output:
Array
(
[Title 3] => Cell 3 Value
[Title 1] => Cell 1 Value
[Title 2] => Cell 2 Value
)
Try this:
$result = array_flip($excel_db_relation);
array_walk($result, function(&$value, $key) use ($db_result) {
$value = $db_result[$value];
});
var_dump($result);
But make sure that all keys exist beforehand.
This worked for me:
<?php
//...
usort($excel_arr, function ($a, $b) { return strnatcmp($a[0], $b[0]); });
$result = [];
// traverse the *title* column in the sorted $excel_arr
foreach (array_column($excel_arr, 1) as $a) {
// could use array_flip to speed up this test, though
// this can be problematic if the values aren't *good* array keys
$k = array_search($a, $excel_db_relation);
// if there is a key and it also exists in $db_result
if (false !== $k && array_key_exists($k, $db_result)) {
// assign it to the final result
$result[$a] = $db_result[$k];
}
}
print_r($result);
I am trying to remove a key/value pair from an array but it does not seem to work. Basically, I make an API call which returns JSON. As such I do
$tempArray = json_decode($projects, true);
If I output $tempArray I see something like this
array:2 [
0 => array:9 [
"id" => 4
"name" => "Some Project Name"
"value" => "234"
"user_id" => "1"
"client_id" => "97"
"contact" => "Jane Berry"
]
1 => array:9 [
"id" => 3
"name" => "Another Project Name"
"value" => "6"
"user_id" => "1"
"client_id" => "97"
"contact" => "John Doe"
]
]
I essentially need to remove the value element so I do this
unset($tempArray['value']);
If I output $tempArray after the unset, it displays exactly the same as before, with the value element and value there.
What do I need to do to completely remove this from my array?
Thanks
unset will not look recursivly to sub-array to remove the key value. Only if you have at first level a key named value will be removed. In your array first level keys are: 0 and 1.
So to remove value from all sub-arrays you have to go throw all items from the array and unset it. You can do this with a simple foreach.
foreach($tempArray as $key => $data) {
unset($data['value']);
$tempArray[$key] = $data; //Overwrite old data with new with value unset.
}
Now you will not have value key in sub-array items.
As per my comment, you have no key called 'value' which is a top level key in your array. If you array looked like this:
$myArray = array(
"value" => "My Value to delete",
"anotherKey" => "hello world",
);
Then you could do unset($myArray['value']); and you would remove the key and value. In your case, the key you are looking for is nested under a numeric key [0] or [1]. You could reference these specifically like this:
unset($tempArray[0]['value']);
but what I imagine you are looking to achieve is to remove any trace of the key value from your array in which case you would be better off doing something like this:
foreach($tempArray as &$nestedArray){
unset($nestedArray['value']);
}
Note the & symbol before the $nestedArray. This means 'pass by value' and will actually update the $tempArray in a single line without the need for anything else.
Further Reading:
PHP Docs - Arrays
PHP Docs - Foreach loop
PHP Docs - Pass by reference
I have following Array
$arr = array(1 => 1, "1" => 50);
When I execute count() on it, it gives me strange answer: 1
echo count($arr);
Whereas an array $arr has two elements.
Why?
It is due to Type Casting . Check Example #2 Type Casting and Overwriting example in Arrays .
If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten .
$arr = array(1 => 10, "1" => 20);
var_dump( $arr );
Displays :
array (size=1)
1 => int 20
And so :
echo count( $arr );
Displays :
1
Which is correct .
If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.As all the keys in the below example are cast to 1, the value will be overwritten on every new element.
Sample Code:
$array = array(
1 => "a",
"1" => "b"
);
var_dump($array);
echo count($array);
Sample output:
array(1) {
[1]=>
string(1) "b"
}
1
For details have a look here:http://nz1.php.net/manual/en/language.types.array.php
if you change the "1" to "2" it will count 2. The problem is the fact that you choose the first element in the array to be 1 then you choose it to be 50, so in the final, the array will have one element, which is 50.
See it here!
This question already has answers here:
Remove all elements from array that do not start with a certain string
(10 answers)
Closed 9 years ago.
I have a large SQL query which returns aggregate data.
My returned array is something like this:
array(37) { // I get 37 arrays returned
[0] => array(10) {
["groupId"] => string(1) "3" // the first param is just an id
["sessionCount84"] => string(1) "0"
["sessionCount1"] => string(1) "1"
} ...
Each sub-array will contains multiple keys with the word 'sessionCount' and a number following that and there could be many of them.
Is there a way to get all the values for keys which contain the words 'sessionCount[someNumber]" ?
I tried the array_keys function in php, but that requires an exact word match, meaning I would need to know the number following 'sessionCount' in the key, so I'd need to get all the keys that contain that word first somehow.
$tmp = array();
foreach ($array as $sub)
foreach ($sub as $k => $v)
if (substr($k, 0, 12) == 'sessionCount')
$tmp[$k] = $v;
Perhaps something like this will help.
$myArray = array(37) { [0]=> // I get 37 arrays returned
array(10) { ["groupId"]=> string(1) "3" // the first param is just an id
["sessionCount84"]=> string(1) "0"
["sessionCount1"]=> string(1) "1" } ...
$sessions = array();
array_map(function($session) use (&$sessions) {
foreach ($session as $key => $value) {
if ($key starts with "sessionCount") // I'm going to leave that up to you
$sessions[$key] = $value;
}
}, $myArray);
without changing the array you can only do this by brute force.. aka. try "sessionCount[0-999]"..
a different approach would be to use strcmp() on the array keys like so:
foreach($array as $key => $value)
if(!strcmp($key,"sessionCount"))
dosomething($key,$value);
or loop through your array once and restructure it to something like this:
array() {
["sessionCount"] => array() {
[84] => "",
[1] => "",
}
}
..after that finding all the keys you require should be a walk in the park. ;)
here is the code im having trouble with
$key = array(
"0" => "sss",
"1" => "wst",
"2" => "sfv",
"3" => "lac",
"4" => "sgv",
"5" => "lgb",
"6" => "ant"
);
$urls = array(
"0" => "http://www.sarmenhb.com/index.php?key=",
"1" => "http://www.navidoor.com/index.php?key=",
"2" => "http://www.worldexchange.com/index.php?key=",
"3" => "http://www.iaddesign.com/index.php?key=",
"4" => "http://www.iadesignandstudio.com/index.php?key=",
"5" => "http://www.redlineautoleasing.com/index.php?key="
);
for($a=0;$a <= count($urls);$a++) {
foreach($key as $keys) {
print $urls[$a].$keys[$a]."<br/>";
}
}
print "<br/><br/>";
i am trying to make the output look like this:
http://www.sarmenhb.com/index.php?key=sss
http://www.navidoor.com/index.php?key=sss
http://www.worldexchange.com/index.php?key=sss
http://www.iaddesign.com/index.php?key=sss
http://www.iadesignandstudio.com/index.php?key=sss
http://www.redlineautoleasing.com/index.php?key=sss
http://www.sarmenhb.com/index.php?key=wst
http://www.navidoor.com/index.php?key=wst
http://www.worldexchange.com/index.php?key=wst
http://www.iaddesign.com/index.php?key=wst
http://www.iadesignandstudio.com/index.php?key=wst
http://www.redlineautoleasing.com/index.php?key=wst
etc including all key values included as a value the the param key
ive removed the origional urls to prevent url hacking but how can i print an output like that?
the output i keep getting is key=s or key=w the whole key value isnt displaying. along with an error of Notice: Uninitialized string offset: 3 in D:\wamp\www\MVC\t.php on line 32
please help
thank alot!
foreach($key as $string)
{
foreach($urls as $address)
{
echo $address . $string . "<br/>";
}
}
I would simply do two foreach statements:
foreach($urls as $url) {
foreach($keys as $key) {
print $url.$key."\n";
}
}
I also recommend you to pluralize the name of your arrays for simple readability, check the output here.
That's because you're printing $keys[$a]. $keys is a string from your array, and $a would just get a single character. You can select characters in strings the same way you select variable from array.
If you remove the square brackets it should work.
print $urls[$a].$keys."<br/>";
Remove the foreach loop and change $keys[$a] to $key[$a].