I have this array:
$array = array(
[0] => "obm=SOME_TEXT",
[1] => "sbm=SOME_TEXT",
[2] => "obm=SOME_TEXT"
);
How can I remove array's element(s) containing value obm or sbm (which is always at the top of the string in the array) and update indexes?
Example 1:
print_r(arrRemove("smb", $array));
Output:
$array = array(
[0] => "obm=SOME_TEXT",
[1] => "obm=SOME_TEXT"
);
Example 2:
print_r(arrRemove("omb", $array));
Output:
$array = array(
[0] => "sbm=SOME_TEXT"
);
You can simply loop through the array using a foreach and then use strpos() to check if the array contains the given input string, and array_values() to update the indexes:
function arrRemove($str, $input) {
foreach ($input as $key => $value) {
// get the word before '='
list($word, $text) = explode('=', $value);
// check if the word contains your searchterm
if (strpos($word, $str) !== FALSE) {
unset($input[$key]);
}
}
return array_values($input);
}
Usage:
print_r(arrRemove('obm', $array));
print_r(arrRemove('sbm', $array));
Output:
Array
(
[0] => sbm=SOME_TEXT
)
Array
(
[0] => obm=SOME_TEXT
[1] => obm=SOME_TEXT
)
Demo!
Maybe something like this?
$newarray = array_values(array_filter($oldarray, function($value){
return strpos($value, 'obm') !== 0;
}
));
This is handled by PHP
php.net/manual/en/function.array-pop.php
array_pop() pops and returns the last value of the array , shortening the array by one element.
Related
I need the Id if the 'Final' text match on this array. Like this for array one 288617 and for array two 288031.
Array
(
[0] => a:4:{i:0;s:11:"Demo Course";i:1;s:6:"288616";i:2;s:10:"Final Exam";i:3;s:6:"288617";}
)
Array
(
[0] => a:29:{i:0;s:16:"Sage 50 Accounts";i:1;s:6:"287967";i:2;s:6:"278823";i:3;s:6:"278824";i:4;s:6:"278825";i:5;s:6:"278826";i:6;s:6:"278856";i:7;s:6:"278857";i:8;s:6:"278858";i:9;s:6:"278859";i:10;s:6:"278860";i:11;s:6:"278861";i:12;s:6:"278862";i:13;s:6:"279608";i:14;s:6:"279609";i:15;s:6:"279610";i:16;s:6:"279611";i:17;s:6:"278821";i:18;s:6:"279612";i:19;s:6:"279613";i:20;s:6:"279681";i:21;s:6:"279677";i:22;s:6:"279678";i:23;s:6:"279679";i:24;s:6:"279680";i:25;s:9:"Mock Exam";i:26;s:6:"288030";i:27;s:10:"Final Exam";i:28;s:6:"288031";}
)
I have tried with this code, but can't work.
$search_text = 'Final';
array_filter($array, function($el) use ($search_text) {
return ( strpos($el['text'], $search_text) !== false );
});
First you have to unserialize that text. Then the simplest way is to loop and check for the text and then take the next element:
$array[0] = unserialize($array[0]);
$search_text = 'Final';
foreach($array[0] as $key => $value){
if(strpos($value, $search_text) !== false) {
$result = $array[0][$key+1];
break;
}
}
This assumes that the array is paired the way you have shown:
Array
(
[0] => Demo Course
[1] => 288616
[2] => Final Exam
[3] => 288617
)
With your second array it would only return the first ID 287967 if you search on Sage.
Try end function.
This function return the last element of your array
$array = ['sample1', 'sample2', ... ,'Final';
$search_text = 'Final';
if(end($aray) == $search_text){
// find
}else{
// not found
}
I am not sure why the following does not work. I get the above error (topic):
$array = array (); //something goes in here
function del_space(array $a){
foreach($a as $key => $value){
preg_replace("/; +/", "", $value);
}
}
$no_space = array_map("del_space", $array);
array_map() loops $array for you and since so I am assuming that each item inside of $array is not an array object but del_space() requires an array to be passed in to it.
It sounds like you have:
$array = array( 'some item' ); // Fails
but you need something like:
$array = array( array( 'some item' ) ); // Success
if you wish to use array_map()
Your function del_space takes an array as the argument. array_map takes every element of the array (second argument) itself, and sends it to the callback (first argument). So unless if you have an array of arrays, this would not work. Your example should look like this:
$array = ['lblab; la'];
function del_space($a){
return preg_replace("/; +/", "", $a);
}
$no_space = array_map("del_space", $array);
print_r($no_space);
Gives output:
Array ( [0] => lblab;la)
If you want to pass an array of arrays, than the input should look like this:
$array = [
['blabla; bla'],
['blabla2; bla2'],
];
function del_space(array $a){
foreach($a as $key => $value){
$a[$key] = preg_replace("/; +/", "", $value);
}
return $a;
}
$no_space = array_map("del_space", $array);
print_r($no_space);
With the output:
Array ( [0] => Array ( [0] => blablabla ) [1] => Array ( [0] => blabla2bla2 ) )
I have an array that looks like this
$array = array(
array("John","Smith","1"),
array("Bob","Barker","2"),
array("Will","Smith","2"),
array("Will","Smith","4")
);
In the end I want the array to look like this
$array = array(
array("John","Smith","1"),
array("Bob","Barker","2"),
array("Will","Smith","2")
);
The array_unique with the SORT_REGULAR flag checks for all three value. I've seen some solutions on how to remove duplicates based on one value, but I need to compare the first two values for uniqueness.
Simple solution using foreach loop and array_values function:
$arr = array(
array("John","Smith","1"), array("Bob","Barker","2"),
array("Will","Smith","2"), array("Will","Smith","4")
);
$result = [];
foreach ($arr as $v) {
$k = $v[0] . $v[1]; // considering first 2 values as a unique key
if (!isset($result[$k])) $result[$k] = $v;
}
$result = array_values($result);
print_r($result);
The output:
Array
(
[0] => Array
(
[0] => John
[1] => Smith
[2] => 1
)
[1] => Array
(
[0] => Bob
[1] => Barker
[2] => 2
)
[2] => Array
(
[0] => Will
[1] => Smith
[2] => 2
)
)
Sample code with comments:
// array to store already existing values
$existsing = array();
// new array
$filtered = array();
foreach ($array as $item) {
// Unique key
$key = $item[0] . ' ' . $item[1];
// if key doesn't exists - add it and add item to $filtered
if (!isset($existsing[$key])) {
$existsing[$key] = 1;
$filtered[] = $item;
}
}
For fun. This will keep the last occurrence and eliminate the others:
$array = array_combine(array_map(function($v) { return $v[0].$v[1]; }, $array), $array);
Map the array and build a key from the first to entries of the sub array
Use the returned array as keys in the new array and original as the values
If you want to keep the first occurrence then just reverse the array before and after:
$array = array_reverse($array);
$array = array_reverse(array_combine(array_map(function($v) { return $v[0].$v[1]; },
$array), $array));
I have an array with "foo.bar.baz" as key names in the array. Is there a handy way to turn this array into a multidimensional array (using each "dot level" as key for the next array)?
Actual output: Array([foo.bar.baz] => 1, [qux] => 1)
Desired output: Array([foo][bar][baz] => 1, [qux] => 1)
Code example:
$arr = array("foo.bar.baz" => 1, "qux" => 1);
print_r($arr);
Solution:
<?php
$arr = array('foo.bar.baz' => 1, 'qux' => 1);
function array_dotkey(array $arr)
{
// Loop through each key/value pairs.
foreach ( $arr as $key => $value )
{
if ( strpos($key, '.') !== FALSE )
{
// Reference to the array.
$tmparr =& $arr;
// Split the key by "." and loop through each value.
foreach ( explode('.', $key) as $tmpkey )
{
// Add it to the array.
$tmparr[$tmpkey] = array();
// So that we can recursively continue adding values, change $tmparr to a reference of the most recent key we've added.
$tmparr =& $tmparr[$tmpkey];
}
// Set the value.
$tmparr = $value;
// Remove the key that contains "." characters now that we've added the multi-dimensional version.
unset($arr[$key]);
}
}
return $arr;
}
$arr = array_dotkey($arr);
print_r($arr);
Outputs:
Array
(
[qux] => 1
[foo] => Array
(
[bar] => Array
(
[baz] => 1
)
)
)
my php array looks like this:
Array (
[0] => dummy
[1] => stdClass Object (
[aid] => 1
[atitle] => Ameya R. Kadam )
[2] => stdClass Object (
[aid] => 2
[atitle] => Amritpal Singh )
[3] => stdClass Object (
[aid] => 3
[atitle] => Anwar Syed )
[4] => stdClass Object (
[aid] => 4
[atitle] => Aratrika )
) )
now i want to echo the values inside [atitle].
to be specific i want to implode values of atitle into another variable.
how can i make it happen?
With PHP 5.3:
$result = array_map(function($element) { return $element->atitle; }, $array);
if you don't have 5.3 you have to make the anonymous function a regular one and provide the name as string.
Above I missed the part about the empty element, using this approach this could be solved using array_filter:
$array = array_filter($array, function($element) { return is_object($element); });
$result = array_map(function($element) { return $element->atitle; }, $array);
If you are crazy you could write this in one line ...
Your array is declared a bit like this :
(Well, you're probably, in your real case, getting your data from a database or something like that -- but this should be ok, here, to test)
$arr = array(
'dummy',
(object)array('aid' => 1, 'atitle' => 'Ameya R. Kadam'),
(object)array('aid' => 2, 'atitle' => 'Amritpal Singh'),
(object)array('aid' => 3, 'atitle' => 'Anwar Syed'),
(object)array('aid' => 4, 'atitle' => 'Aratrika'),
);
Which means you can extract all the titles to an array, looping over your initial array (excluding the first element, and using the atitle property of each object) :
$titles = array();
$num = count($arr);
for ($i=1 ; $i<$num ; $i++) {
$titles[] = $arr[$i]->atitle;
}
var_dump($titles);
This will get you an array like this one :
array
0 => string 'Ameya R. Kadam' (length=14)
1 => string 'Amritpal Singh' (length=14)
2 => string 'Anwar Syed' (length=10)
3 => string 'Aratrika' (length=8)
And you can now implode all this to a string :
echo implode(', ', $titles);
And you'll get :
Ameya R. Kadam, Amritpal Singh, Anwar Syed, Aratrika
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
echo $item->atitle;
}
}
to get them into an Array you'd just need to do:
$resultArray = array();
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
$resultArray[] = $item->atitle;
}
}
Then resultArray is an array of all the atitles
Then you can output as you'd wish
$output = implode(', ', $resultArray);
What you have there is an object.
You can access [atitle] via
$array[1]->atitle;
If you want to check for the existence of title before output, you could use:
// generates the title string from all found titles
$str = '';
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$str .= $v->title;
}
}
echo $str;
If you wanted these in an array it's just a quick switch of storage methods:
// generates the title string from all found titles
$arr = array();
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$arr[] = $v->title;
}
}
echo implode(', ', $arr);
stdClass requires you to use the pointer notation -> for referencing whereas arrays require you to reference them by index, i.e. [4]. You can reference these like:
$array[0]
$array[1]->aid
$array[1]->atitle
$array[2]->aid
$array[2]->atitle
// etc, etc.
$yourArray = array(); //array from above
$atitleArray = array();
foreach($yourArray as $obj){
if(is_object($obj)){
$atitleArray[] = $obj->aTitle;
}
}
seeing as how not every element of your array is an object, you'll need to check for that.