Remove characters from Array values - php

Thanks guys.
I've been towing over this one for over a day now and it's just too difficult for me! I'm trying to remove the last 3 characters from each value within an array. Currently, I've tried converting to a string, then doing the action, then moving into a new array... can't get anything to work. Someone suggested this, but it doesn't work. I need an array of postcodes, "EC1 2AY, EC3 4XW..." converting to "EC1, EC3, ..." and it be back in an Array!!
implode(" ",array_map(function($v){ return ucwords(substr($v, 0, -3)); },
array_keys($area_elements)));
This hasn't worked, and obviously when I converted to a string and do a trim function, it will only take the last 3 characters from the last "variable" in the string.
Please send HELP!

If you want an array back, you shouldn't implode. You are almost there:
$area_elements = ['EC1 2AY', 'EC3 4XW'];
$result = array_map(function($v){
return trim(substr($v, 0, -3));
}, $area_elements);
var_dump($result);
Output:
array(2) {
[0]=>
string(3) "EC1"
[1]=>
string(3) "EC3"
}

Another solution:
altering array by reference.
Snippet
$area_elements = ['EC1 2AY', 'EC3 4XW'];
foreach($area_elements as &$v){
$v = substr($v, 0, -4);
}
print_r($area_elements);
Output
Array
(
[0] => EC1
[1] => EC3
)
Live demo
Pass by reference docs

Related

PHP array containing 0/

hi I have array of elements containing pattern like
$arr = array ('0/' ,'0/12/3','1/2')
i need to have array of "0/" elements i've tried to use command
arr_with_zero_slash = preg_grep('#$[0-9]/$#',$arr)
but function works only witch pattern like 1/ , 2/ and so one. This is because 0/ is treated as special sign but i dont know how to deal with that. Any ideas?
I think this is what you mean:
Cycle through array $arr using a foreach-loop, and unset (remove) all elements that don't start with '0/'...
$arr = array ('0/' ,'0/12/3','1/2');
foreach($arr as $key=>$value){
if(substr($value,0,2)<>"0/"){
unset($arr[$key]);
}
}
With:
$arr = array ('0/' ,'0/12/3','1/2')
this will be the outcome:
array(2) { [0]=> string(2) "0/" [1]=> string(6) "0/12/3" }
If you want to get all elements starting with 0/ try this:
<?php
$arr = array ('0/' ,'0/12/3','1/2', '1/0/4');
$arr_with_zero_slash = preg_grep('#^0/#',$arr);
print_r($arr_with_zero_slash);
This will output
Array (
[0] => 0/
[1] => 0/12/3
)
Removed the first $ since it's a meta-character.
Changed [0-9] to 0, since you only want 0/ and not 1/, 2/ etc.
Removed the second $ since you also want 0/12/3.

How to remove element from non-associative array in php

I'm trying to remove specific element from php array with unset function. Problem is that when I var_dump array it shows all indexes (not good) but If I try to var_dump specific index PHP throws warning (good).
$a = [
'unset_me',
'leave_me',
'whatever',
];
unset($a['unset_me']);
var_dump($a);
/**
array(3) {
[0]=>
string(8) "unset_me"
[1]=>
string(8) "leave_me"
[2]=>
string(8) "whatever
*/
var_dump($a['unset_me']); // Undefined index: unset_me
Question is why php behave like this and how to remove index properly?
One more solution:
$arr = array('unset_me','leave_me','whatever',);
print_r($arr);
// remove the elements that you want
$arr = array_diff($arr, array("unset_me"));
print_r($arr);
You can try this with array_search -
unset($a[array_search('unset_me', $a)]);
If needed then add the checks like -
if(array_search('unset_me', $a) !== false) {
unset($a[array_search('unset_me', $a)]);
}
Demo
$arr = array('unset_me','leave_me','whatever',);
print_r($arr);
echo '<br/>';
$key = array_search('unset_me', $arr);
if($key !== false)
unset($arr[$key]);
print_r($arr);
I recently encountered this problem and found this solution helped:
unset($a[array_flip($a)['unset_me']]);
Just to explain what is going on here:
array_flip($a) switches the items for the key. So it would become:
$a = [
'unset_me' => 0,
'leave_me' => 1,
'whatever' => 2,
];
array_flip($a)['unset_me'] therefore resolves to being 0. So that expression is put into the original $a which can then be unset.
2 caveats here:
This would only work for your basic array, if you had an array of objects or arrays, then you would need to choose one of the other solutions
The key that you remove will be missing from the array, so in this case, there will not be an item at 0 and the array would start from 1. If it is important to you, you can do array_values($a) to reset the keys.

Array by expressions

In php I have the following variable which comes from a url:
$data = "data_id=value1/config/value2/config/value3";
It always comes in the following format:
data_id = first value of the parameter to come
/ config / -> which is a kind of parameters tab
second parameter + / config / + etc ...
I want these values ​​to be inserted into an array, i.e., what would happen is the following:
The Wrath php gets the variable $data, would catch the first parameter, in this case e.g. value1 (which'll come after the data_id) and insert it into the array as a vector 1, soon after it takes the / config / and recognizes that it is a separator, thus making it take the value 2 and enter the array, making this loop until the end.
example:
$data = "data_id =fish/config/horse/config/car";
The array will look as follows:
array
{
[0] -> fish
[1] -> horse
[2] -> Car
}
could someone help me?
Assuming data_id is a GET variable, you can do something like this.
$data = $_GET['data_id']
$myArray = explode('/config/', $data);
explode() documentation
<?php
$data = 'data_id=value1/config/value2/config/value3';
list($name, $value) = explode('=', $data, 2);
$result = explode('/config/', $value);
print_r($result);
Example
If the entire thing is a string you can use strpos to get the position of the = character and cut it away using substr. Then simply explode the entire thing with php explode.
$data = "data_id =fish/config/horse/config/car";
$data = explode( "/config/", substr( $data, strpos( $data, '=' )+1 ) );
Will result in:
array(3) {
[0]=>
string(4) "fish"
[1]=>
string(5) "horse"
[2]=>
string(3) "car"
}
strpos()
substr()
explode()

Creating a dynamic PHP array

I am new PHP question and I am trying to create an array from the following string of data I have. I haven't been able to get anything to work yet. Does anyone have any suggestions?
my string:
Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35
I want to dynamically create an array called "My_Data" and have id display something like my following, keeping in mind that my array could return more or less data at different times.
My_Data
(
[Acct_Status] => active
[signup_date] => 2010-12-27
[acct_type] => GOLD
[profile_range] => 31-35
)
First time working with PHP, would anyone have any suggestions on what I need to do or have a simple solution? I have tried using an explode, doing a for each loop, but either I am way off on the way that I need to do it or I am missing something. I am getting something more along the lines of the below result.
Array ( [0] => Acct_Status=active [1] => signup_date=2010-12-27 [2] => acct_type=GOLD [3] => profile_range=31-35} )
You would need to explode() the string on , and then in a foreach loop, explode() again on the = and assign each to the output array.
$string = "Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35";
// Array to hold the final product
$output = array();
// Split the key/value pairs on the commas
$outer = explode(",", $string);
// Loop over them
foreach ($outer as $inner) {
// And split each of the key/value on the =
// I'm partial to doing multi-assignment with list() in situations like this
// but you could also assign this to an array and access as $arr[0], $arr[1]
// for the key/value respectively.
list($key, $value) = explode("=", $inner);
// Then assign it to the $output by $key
$output[$key] = $value;
}
var_dump($output);
array(4) {
["Acct_Status"]=>
string(6) "active"
["signup_date"]=>
string(10) "2010-12-27"
["acct_type"]=>
string(4) "GOLD"
["profile_range"]=>
string(5) "31-35"
}
The lazy option would be using parse_str after converting , into & using strtr:
$str = strtr($str, ",", "&");
parse_str($str, $array);
I would totally use a regex here however, to assert the structure a bit more:
preg_match_all("/(\w+)=([\w-]+)/", $str, $matches);
$array = array_combine($matches[1], $matches[2]);
Which would skip any attributes that aren't made up of letters, numbers or hypens. (The question being if that's a viable constraint for your input of course.)
$myString = 'Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35';
parse_str(str_replace(',', '&', $myString), $myArray);
var_dump($myArray);

php's explode array index

Using php's explode with the following code
$data="test_1, test_2, test_3";
$temp= explode(",",$data);
I get an array like this
array('0'=>'test_1', '1'=>'test_2', 2='test_3')
what I would like to have after explode
array('1'=>'test_1', '2'=>'test_2', 3='test_3')
You could something like this :
$temp = array_combine(range(1, count($temp)), array_values($temp));
uses array_combine() to create array using your existing values (using array_values()) and range() to create a new range from 1 to the size of your array
Working example here
Array indexes start at 0. If you really wanted to have the array start with one, you could explode it, then copy it to another array with your indexes defined as starting at 1 - but why?
You could use this possibly (untested)
$newArray=array_unshift($temp,' ');
unset($newArray[0]);
it is impossible using explode.
for($i = count($temp) - 1; $i >= 0; $i--)
$temp[$i + 1] = $temp[$i];
unset($temp[0]);
You couldn't do it directly, but this will do what you're after:
$temp=explode(',',',' . $data);
unset($temp[0]);
var_dump($temp);
array(3) {
[1]=>
string(6) "test_1"
[2]=>
string(7) " test_2"
[3]=>
string(7) " test_3"
}
Lloyd Watkin's answer makes the fewest function calls to achieve the expected result. It is certainly a superior answer to ManseUK's method which uses four functions in its one-liner after the string has been exploded.
Since this question is nearly 5 years, old there should be something valuable to add if anyone dare to chime in now...
I have two things to address:
The OP and Lloyd Watkins both fail to assign the correct delimiter to their explode method based on the sample string. The delimiter should be a comma followed by a space.
Sample Input:
$data="test_1, test_2, test_3";
No one has offered a one-liner solution that matches Lloyd's two-function approach. Here that is: (Demo)
$temp=array_slice(explode(", ",", $data"),1,null,true);
This two-function one-liner prepends the $data string with a comma then a space before exploding it. Then array_slice ignores the first empty element, and returns from the second element (1) to the end (null) while preserving the keys (true).
Output as desired:
array(
1 => 'test_1',
2 => 'test_2',
3 => 'test_3',
)

Categories