I want to add to every IP address from array +1 number. I know about bcadd(); but I can't make it work as every IP address has different length and I just need to increase the last number of it.
For example:
array("194.32.14.152", "4.189.23.35", etc...);
... would become:
array("194.32.14.153", "4.189.23.36", etc...);
Now maybe I need to apply str_pad(); to match the last dot?
Any help would be appreciated.
preg_replace_callback(), IMO, is the most succinct and appropriate approach. When there is a single, native function that does it all, why do anything else?
Match the final sequence of digits and so long as it is not 255, increment the substring.
Code: (Demo)
$ips = ["194.32.14.199", "4.189.23.35", "4.189.23.255"];
var_export(preg_replace_callback('~\d+$(?<!255)~',
function($m) {
return ++$m[0];
},
$ips)
);
From PHP7.4+, the syntax becomes more brief by way of arrow syntax.
var_export(preg_replace_callback('~\d+$(?<!255)~', fn($m) => ++$m[0], $ips));
Both snippets produce:
array (
0 => '194.32.14.200',
1 => '4.189.23.36',
2 => '4.189.23.255',
)
The pattern:
\d+ #match 1 or more digits
$ #match the end of the string
(?<!255) #lookbehind to ensure the matched number is not literally 255
In using this pattern, you do not bother handling 255, and you increment all other numbers that are matched.
You can map your array to your new IP addresses. In the map method, you can split the current string by . using explode(). Then, to get the last number from your IP you can use array_pop, which you can then cast to an integer so that you can add one to it. You can then array_push() this updated value onto your parts array, and join each part in your array back together using implode().
See example below:
$arr = array("194.32.14.152", "4.189.23.35", "4.189.23.255");
$res = array_map(function($v) { // Example, let $v = "194.32.14.152";
$parts = explode('.', $v); // "194.32.14.152" -> ["194", "32", "14", "152"];
array_push($parts, min((int) array_pop($parts)+1, 255)); // ["194", "32", "14", 153]
return implode('.', $parts); // "194.32.14.153"
}, $arr);
print_r($res); // ["194.32.14.153", "4.189.23.36", "4.189.23.255"]
Another solution using built-in ip2long and long2ip and PHP bitwise operators
<?php
$ips = array("194.32.14.152", "4.189.23.35", "4.51.11.255");
$newIps = [];
foreach($ips as $ipString){
$ip = ip2long($ipString);
$lastByte = ($ip & 0x000000FF)+1;
$lastByte = $lastByte > 255 ? 255 : $lastByte;
$newIps[]= long2ip(( $lastByte ) | (0xFFFFFF00 & $ip ) );
}
var_dump($newIps);
This outputs
array(3) {
[0]=>
string(13) "194.32.14.153"
[1]=>
string(11) "4.189.23.36"
[2]=>
string(11) "4.51.11.255"
}
Live demo https://3v4l.org/iZeAR
Related
I have an stdclass object like this:
{
"type": "photo",
"photo": {
"id": id,
"album_id": album_id,
"owner_id": owner_id,
"photo_75": "https://example.com/random_unique_string/random_unique_name.jpg",
"photo_130": "https://example.com/random_unique_string/random_unique_name.jpg",
"photo_604": "https://example.com/random_unique_string/random_unique_name.jpg",
"photo_807": "https://example.com/random_unique_string/random_unique_name.jpg",
"photo_1280": "https://example.com/random_unique_string/random_unique_name.jpg",
"photo_2560": "https://example.com/random_unique_string/random_unique_name.jpg",
"width": 2560,
"height": 1440,
"text": "",
"date": 1517775329,
"access_key": "key"
}
The more complete look is on this pic:
I have my code structure like this:
foreach ( $response->posts as $key => $element ) {
if ( isset ($element->attachments) ) {
foreach ( $element->attachments as $key_att => $attachment ) {
if ( $attachment->type == 'photo' ) {
//get the value of the photo with the maximum resolution
}
}
}
}
How do I get only the value of photo_2560 in this case, pointing it to the photo_ ending with the maximum numeric value? max only works with completely numeric keys... Perhaps would need a regex, but I'm weak at that. Thanks for the help.
P. S. I asked about an array and not an object initially, so the answers given are valid, I made a mistake myself. The initial name of the question was get array key ending in highest number but not numerical. I then edited it to reflect my specific issue. Sorry about the confusion.
Here is what I would do using the little known preg_grep function:
$array = [
"photo_75"=> "https=>//example.com/random_unique_string/random_unique_name.jpg",
"photo_130"=> "https=>//example.com/random_unique_string/random_unique_name.jpg",
"photo_604"=> "https=>//example.com/random_unique_string/random_unique_name.jpg",
"photo_807"=> "https=>//example.com/random_unique_string/random_unique_name.jpg",
"photo_1280"=> "https=>//example.com/random_unique_string/random_unique_name.jpg",
"photo_2560"=> "https=>//example.com/random_unique_string/random_unique_name.jpg",
"width"=> 2560,
"height"=> 1440,
"text"=> "",
"date"=> 1517775329,
"access_key"=> "key"
];
$array = preg_grep('/^photo_\d+$/', array_keys($array));
sort($array, SORT_NATURAL);
print_r(end($array));
Output
photo_2560
Sandbox
Preg Grep lets you search an array using a regular expression, It's sort of like using array filter and preg_match
$array = array_filter($array, function($item){
return preg_match('/^photo_\d+$/', $item);
});
But obviously much shorter. Like array filter it's mostly for use against the values and not the keys, but we can use array_keys to get around this. Array Keys returns an array of the keys as the new arrays value array(0=>'key', ..) which is exactly what we want.
UPDATE
Based on this comment:
Is there an alternative of array_keys for an object? Because I confused it with an array, unfortunately.
No but you can cast it (array)$obj to an array if the properties are public. We can demonstrate this easily:
class foo{
public $bar = 'hello';
}
print_r(array_keys((array)(new foo)));
Output
array(
0 => 'bar' //which is the key 'bar' or the property named $bar
)
Sandbox
While it's not "ideal" it will work.
UPDATE1
I made edits to my question, please take a look. I don't understand how to apply your example in this case :(
I think it's $attachment->photo in your code, it's really hard to tell in the image. It's whereever the 'stuff' at the very top of you question came from, your example data.
In anycase with your code you would do something like this:
foreach ( $response->posts as $key => $element ) {
if ( isset ($element->attachments) ) {
foreach ( $element->attachments as $key_att => $attachment ) {
if ( $attachment->type == 'photo' ) {
//new code
$array = preg_grep('/^photo_\d+$/', array_keys((array)$attachment->photo));
sort($array, SORT_NATURAL);
$result = end($array);
print_r($result);
}
} //end foreach
}
}//end foreach
By the way the Regex I am using ^photo_\d+$ is basically this
^ match the start of the string
photo_ match "photo_" litterally
\d+ match one or more digits
$ match the end of the string.
Note the ^ can have different meaning depending where it is, for example if its in a character class [0-9] (A range of characters 0 to 9 same as \d) like this [^0-9] it means NOT so it makes the character class match everything but what is in it. Or "negation". Which is a bit confusing, but that is how it works. In this case it would be anything NOT a digit.
By using the ^ and $ we are saying that our Regex must match the whole string. So we can avoid things like somephoto_79890_aab which if we didn't have the start and end markers our Regex photo_\d+ would match this part some[photo_79890]_aab.
Cheers.
Regex won't tell you what the highest number is. But, these "photo_N" keys can be sorted using natural order.
You didn't mention the name of your variable, so I'll just assume $array here for the sake of convenience.
Let's first get only the "photo_N" elements from the array:
$photos = array_filter(
$array['photo'],
function($key) {
return substr($key, 0, 6) === "photo_";
},
ARRAY_FILTER_USE_KEY
);
We can now sort the result of that by key, using natural order:
ksort($photos, SORT_NATURAL);
This should have put the photo with the highest numerical key at the end, so you can get its value using:
$photo = end($photos);
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
If I have two strings in an array:
$x = array("int(100)", "float(2.1)");
is there a simple way of reading each value as the number stored inside as a number?
The reason is I am looking at a function (not mine) that sometimes receives an int and sometimes a float. I cannot control the data it receives.
function convertAlpha($AlphaValue) {
return((127/100)*(100-$AlphaValue));
}
It causes an error in php
PHP Notice: A non well formed numeric value encountered
which I want to get rid of.
I could strip the string down and see what it is and do an intval/floatval but wondered if there was a neat way.
UPDATE:
Playing about a bit I have this:
function convertAlpha($AlphaValue)
{
$x = explode("(", $AlphaValue);
$y = explode(")", $x[1]);
if ($x[0] == "int") {
$z = intval($y[0]);
}
if ($x[0] == "float") {
$z = floatval($y[0]);
}
return((127/100)*(100-$z)); }
This which works but it just messy.
<?php
$x = array("int(100)", "float(2.1)");
$result = [];
foreach($x as $each_value){
$matches = [];
if(preg_match('/^([a-z]+)(\((\d+(\.\d+)?)\))$/',$each_value,$matches)){
switch($matches[1]){
case "int": $result[] = intval($matches[3]); break;
case "float": $result[] = floatval($matches[3]);
}
}
}
print_r($result);
OUTPUT
Array
(
[0] => 100
[1] => 2.1
)
The simplest would simply be to make the array as you need it, so instead of
$x = array("int(100)", "float(2.1)");
you have:
$x = [100, 2.1];
but as this is not what you want you got two choices now. One, is to use eval(), for example:
$x = ['(int)100', '(float)2.1'];
foreach ($x as $v) {
var_dump(eval("return ${v};"));
}
which will produce:
int(100)
double(2.1)
As you noticed, source array is bit different because as there is no such function in PHP as int() or float(), so if you decide to use eval() you need to change the string to be valid PHP code with the casting as shown in above example, or with use of existing intval() or floatval() functions. Finally, you can parse strings yourself (most likely with preg_match()), check for your own syntax and either convert to PHP to eval() it or just process it in your own code, which usually is recommended over using eval().
The way I would do it is by using a regex to determine the type and value by 2 seperate groups:
([a-z]+)\((\d*\.?\d*)\)
The regex captures the alphanumeric characters up and until the first (. It then looks for the characters between the ( and ) with this part: \d*\.?\d*.
The digit-part of the regex accepts input like: 12.34, .12, 12. and 123
$re = '/([a-z]+)\((\d*\.?\d*)\)/m';
$input_values = array('int(100)', 'float(2.1)');
foreach($input_values as $input) {
preg_match_all($re, $input, $matches, PREG_SET_ORDER, 0);
var_dump($matches);
}
Which leads to the output below. As you can see, there is the type in the [1] slot and the number in the [2] slot of the array
array(1) {
[0]=>
array(3) {
[0]=>
string(8) "int(100)"
[1]=>
string(3) "int"
[2]=>
string(3) "100"
}
}
array(1) {
[0]=>
array(3) {
[0]=>
string(10) "float(2.1)"
[1]=>
string(5) "float"
[2]=>
string(3) "2.1"
}
}
You can then use a check to perform the casting like:
$value;
if(matches[1] === "int") {
$value = intval($matches[2]);
} elseif (matches[1] === "float") {
$value = floatval($matches[2]);
}
The latter code still needs error handling, but you get the idea. Hope this helps!
PHP is historically typed against strings so it's pretty strong with cases like these.
$x = array("int(100)", "float(2.1)");
^^^ ^^^
You can actually turn each of those strings into a number by multiplying the substring starting after the first "(" with just one to turn it into a number - be it integer or float:
$numbers = array_map(function($string) {
return 1 * substr(strstr($string, '('), 1);
}, $x);
var_dump($numbers);
array(2) {
[0] =>
int(100)
[1] =>
double(2.1)
}
That is PHP takes everthing numberish from a string until that string seems to end and will calculate it into either an integer or float (var_dump() shows float as double). It's just consuming all number parts from the beginning of the string.
Not saying existing answers are wrong per-se, but if you ask that as a PHP question, PHP has a parser very well for that. My suggestion is to just remove the superfluous information from the beginning of the string and let PHP do the rest.
If you want it more precise, regular expressions are most likely your friend as in the yet top rated answer, still combined with PHP will give you full checks on each string:
$numbers = array_map(function($string) {
$result = preg_match('~^(?:int|float)\(([^)]+)\)$~', $string, $group) ? $group[1] : null;
return null === $result ? $result : 1 * $result;
}, $x);
So all non int and float strings will be turned into NULLs (if any).
I have an array of the format
array(
[0]=>x_4556v_7889;
[1]=>y_9908;
[2]=>f_5643u_7865;
)
I need to get output as
array(
[0]=> ([0] =>4556;
[1] =>7889;
)
[1]=>( [0]=>9908;)
[2] =>([0] =>5643;
[1]=>7865;
)
)
how to use strpos and find out the occurance of "_"(underscore) in string and get the next four characters in for loop.
Am getting only the first four digit code the next four digit are not getting.Kindly provide some logic.
Looks like you're trying to find all the numbers. In that case, consider trying this:
$output = array_map(function($item) {
preg_match_all("/\d+/",$item,$m);
return $m[0];
},$input);
Should work just fine :)
This is a regex free solution though..
$arr = array(
0=>'x_4556v_7889;',
1=>'y_9908;',
2=>'f_5643u_7865;'
);
$lettersarr = range('a','z');
array_unshift($lettersarr,'_');
array_unshift($lettersarr,';');
$new_arr=array_map(function ($v) use($lettersarr) {
return explode('#',wordwrap(str_replace($lettersarr,'',$v), 4, "#", true)); },$arr);
print_r($new_arr);
Demonstration
This question already has answers here:
A numeric string as array key in PHP
(11 answers)
Closed 2 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I've come across an old app that uses an id to name type array, for example...
array(1) {
[280]=>
string(3) "abc"
}
Now I need to reorder these, and a var_dump() would make it appear that that isn't going to happen while the keys are integers.
If I add an a to every index, var_dump() will show double quotes around the key, my guess to show it is now a string...
array(1) {
["280a"]=>
string(3) "abc"
}
This would let me easily reorder them, without having to touch more code.
This does not work.
$newArray = array();
foreach($array as $key => $value) {
$newArray[(string) $key] = $value;
}
A var_dump() still shows them as integer array indexes.
Is there a way to force the keys to be strings, so I can reorder them without ruining the array?
YOU CAN'T!!
Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.
Edit:
ACTUALLY YOU CAN!!
Cast sequential array to associative array
$obj = new stdClass;
foreach($array as $key => $value){
$obj->{$key} = $value;
}
$array = (array) $obj;
In most cases, the following quote is true:
Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.
This examples from the PHP Docs
<?php
$array = array(
1 => "a",
"1" => "b",
1.5 => "c",
true => "d",
);
var_dump($array);
?>
The above example will output:
array(1) {
[1]=> string(1) "d"
}
So even if you were to create an array with numbered keys they would just get casted back to integers.
Unfortunately for me I was not aware of this until recently but I thought I would share my failed attempts.
Failed attempts
$arr = array_change_key_case($arr); // worth a try.
Returns an array with all keys from array lowercased or uppercased. Numbered indices are left as is.
My next attempts was to create a new array by array_combineing the old values the new (string)keys.
I tried several ways of making the $keys array contain numeric values of type string.
range("A", "Z" ) works for the alphabet so I though I would try it with a numeric string.
$keys = range("0", (string) count($arr) ); // integers
This resulted in an array full of keys but were all of int type.
Here's a couple of successful attempts of creating an array with the values of type string.
$keys = explode(',', implode(",", array_keys($arr))); // values strings
$keys = array_map('strval', array_keys($arr)); // values strings
Now just to combine the two.
$arr = array_combine( $keys, $arr);
This is when I discovered numeric strings are casted to integers.
$arr = array_combine( $keys, $arr); // int strings
//assert($arr === array_values($arr)) // true.
The only way to change the keys to strings and maintain their literal values would be to prefix the key with a suffix it with a decimal point "00","01","02" or "0.","1.","2.".
You can achieve this like so.
$keys = explode(',', implode(".,", array_keys($arr)) . '.'); // added decimal point
$arr = array_combine($keys, $arr);
Of course this is less than ideal as you will need to target array elements like this.
$arr["280."]
I've created a little function which will target the correct array element even if you only enter the integer and not the new string.
function array_value($array, $key){
if(array_key_exists($key, $array)){
return $array[ $key ];
}
if(is_numeric($key) && array_key_exists('.' . $key, $array)){
return $array[ '.' . $key ];
}
return null;
}
Usage
echo array_value($array, "208"); // "abc"
Edit:
ACTUALLY YOU CAN!!
Cast sequential array to associative array
All that for nothing
You can append the null character "\0" to the end of the array key. This makes it so PHP can't interpret the string as an integer. All of the array functions (like array_merge()) work on it. Also not even var_dump() will show anything extra after the string of integers.
Example:
$numbers1 = array();
$numbers2 = array();
$numbers = array();
$pool1 = array(111, 222, 333, 444);
$pool2 = array(555, 666, 777, 888);
foreach($pool1 as $p1)
{
$numbers1[$p1 . "\0"] = $p1;
}
foreach($pool2 as $p2)
{
$numbers2[$p2 . "\0"] = $p2;
}
$numbers = array_merge($numbers1, $numbers2);
var_dump($numbers);
The resulting output will be:
array(8) {
["111"] => string(3) "111"
["222"] => string(3) "222"
["333"] => string(3) "333"
["444"] => string(3) "444"
["555"] => string(3) "555"
["666"] => string(3) "666"
["777"] => string(3) "777"
["888"] => string(3) "888"
}
Without the . "\0" part the resulting array would be:
array(8) {
[0] => string(3) "111"
[1] => string(3) "222"
[2] => string(3) "333"
[3] => string(3) "444"
[4] => string(3) "555"
[5] => string(3) "666"
[6] => string(3) "777"
[7] => string(3) "888"
}
Also ksort() will also ignore the null character meaning $numbers[111] and $numbers["111\0"] will both have the same weight in the sorting algorithm.
The only downside to this method is that to access, for example $numbers["444"], you would actually have to access it via $numbers["444\0"] and since not even var_dump() will show you there's a null character at the end, there's no clue as to why you get "Undefined offset". So only use this hack if iterating via a foreach() or whoever ends up maintaining your code will hate you.
Use an object instead of an array $object = (object)$array;
EDIT:
I assumed that if they are integers, I
can't reorder them without changing
the key (which is significant in this
example). However, if they were
strings, I can reorder them how they
like as the index shouldn't be
interpreted to have any special
meaning. Anyway, see my question
update for how I did it (I went down a
different route).
Actually they dont have to be in numeric order...
array(208=>'a', 0=> 'b', 99=>'c');
Is perfectly valid if youre assigning them manually. Though i agree the integer keys might be misinterpreted as having a sequential meaning by someone although you would think if they were in a non-numeric order it would be evident they werent. That said i think since you had the leeway to change the code as you updated that is the better approach.
Probably not the most efficient way but easy as pie:
$keys = array_keys($data);
$values = array_values($data);
$stringKeys = array_map('strval', $keys);
$data = array_combine($stringKeys, $values);
//sort your data
I was able to get this to work by adding '.0' onto the end of each key, as such:
$options = [];
for ($i = 1; $i <= 4; $i++) {
$options[$i.'.0'] = $i;
}
Will return:
array("1.0" => 1, "2.0" => 2, "3.0" => 3, "4.0" => 4)
It may not be completely optimal but it does allow you to sort the array and extract (an equivalent of) the original key without having to truncate anything.
Edit:
This should work
foreach($array as $key => $value) {
$newkey = sprintf('%s',$key);
$newArray["'$newkey'"] = $value;
}
Hi we can make the index of the array a string using the following way. If we convert an array to xml then indexes like [0] may create issue so convert to string like [sample_0]
$newArray = array();
foreach($array as $key => $value) {
$newArray["sample_".$key] = $value;
}
All other answers thus far are hacks that either use fragile workarounds that could break between major PHP versions, create unnecessary gotchas by deliberately corrupting keys, or just slow down your code for no benefit. The various functions to sort arrays yet maintain the crucial key associations have existed since PHP 4.
It is pointless stop PHP from using integer keys, it only does so when the integer representation is exactly the same as the string, thus casting an integer key back to string when reading from the array is guaranteed to return the original data. PHP's internal representation of your data is completely irrelevant as long as you avoid the functions that rewrite integer keys. The docs clearly state which array functions will do that.
An example of sorting, without any hacks, that demonstrates how data remains uncorrupted:
<?php
# use string keys to define as populating from a db, etc. would,
# even though PHP will convert the keys to integers
$in = array(
'347' => 'ghi',
'176' => 'def',
'280' => 'abc',
);
# sort by key
ksort($in);
echo "K:\n";
$i = 1;
foreach ($in as $k => $v) {
echo $i++, "\n";
$k = (string) $k; # convert back to original
var_dump($k, $v);
}
# sort by value
asort($in, SORT_STRING);
echo "\nV:\n";
$i = 1;
foreach ($in as $k => $v) {
echo $i++, "\n";
$k = (string) $k;
var_dump($k, $v);
}
# unnecessary to cast as object unless keys could be sequential, gapless, and start with 0
if (function_exists('json_encode')) {
echo "\nJSON:\n", json_encode($in);
}
The output it produces hasn't changed since v5.2 (with only the JSON missing prior to that):
K:
1
string(3) "176"
string(3) "def"
2
string(3) "280"
string(3) "abc"
3
string(3) "347"
string(3) "ghi"
V:
1
string(3) "280"
string(3) "abc"
2
string(3) "176"
string(3) "def"
3
string(3) "347"
string(3) "ghi"
JSON:
{"280":"abc","176":"def","347":"ghi"}