PHP array containing 0/ - php

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.

Related

Remove characters from Array values

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

Value from php array seems incorrect

I am having an issue with understanding why my array containing 3 elements must be sliced into 2 parts each. I wish to access a number I'm pushing into the array only however it seems to print out the index rather than the 'key' value I pushed into it ($number).
I have a 2d array I'm pushing an ID and an integer into, and then sort it :
$array = [[]];
array_push($array, $doc[_id], $number);
array_multisort($array);
I then filter any empty elements:
$array = array_filter($array); //remove null elements
This all works as id expect however the array looks like this by this point:
unrated.array(5)
{
[2]=> object(MongoId)#32 (1)
{ ["$id"]=> string(24) "57b99696ce2350100b000029" }
[3]=> object(MongoId)#31 (1)
{ ["$id"]=> string(24) "57b998ccce2350181700002b" }
[4]=> object(MongoId)#33 (1)
{ ["$id"]=> string(24) "57b99a84ce2350100b00002b" }
[5]=> int(2) [6]=> int(3)
}
Again, this is fine however it means when I loop over the array using the code below it appears to be longer than 3 elements, as I have to slice from 0-6 instead of 0-3:
$array = array_slice($array, 0, 6, true); //only get 3 elements from array
foreach ($array as $key => $value) {
echo $key; //prints out values from 1-5 weirdly.... should just print the $number value
$id = $value->{'$id'};
}
What I am trying to achieve is to find the element in the array with the lowest possible value that was pushed earlier (array_push($array, $doc[_id], $number);) however because I cannot understand why the array is split into 6 rather than 3 parts its even more confusing.
Question in short : How do I access the $number pushed into the array and why is my array 6 seemingly 6 in size when it contains only 3 elements.
Any help would be appreciated, thanks.
To be clear, array_push simply pushes one or more values onto the end of an array. The first argument of array_push is the array you wish to push the value(s) to, and any subsequent argument is a list of values you wish to push. So what you're doing with array_push($array, $doc[_id], $number) is pushing two values ($doc[_id] and $number) to the end of the array $array. array_push will just use the next available index as the key when it adds those values to the array. It will not allow you to specify a key. This is the same thing as doing $array[] = $value.
To specify a key you must assign a value directly to the array key like so: $array[$key] = $value.

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.

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