If I have a string like this:
0+1+0+0+0+0+0+1+0+1+1+1+1+0+0+1+0+1+1+1+1+0+0+1+0+0+1+0+0+0+0+0+0+1+1+0+1+1+0+0+0+1+1+0+1+1+0+1+0+1+1+0+0+0+0+1+0+1+1+0+1+1+1+1
I need it do actually do the math.
So if $a = '0+1+0+0+0+0+0+1'
It would set another variable and set it as:
2
You should never eval strings if you can help it. There's a trivial sane solution for parsing and summing this particular string:
$string = '0+1+...';
$result = array_sum(explode('+', $string));
If you want to support more possible operations than just +, you'd do a slightly more complex preg_split, then loop over the resulting items and evaluate each individual operator and sum or subtract or whatever based on the encountered operator in a loop.
You can use the php eval function as follows.
<?php
$string="0+1+0+0+0+0+0+1+0+1+1+1+1+0+0+1+0+1+1+1+1+0+0+1+0+0+1+0+0+0+0+0+0+1+1+0+1+1+0+0+0+1+1+0+1+1+0+1+0+1+1+0+0+0+0+1+0+1+1+0+1+1+1+1";
eval("\$val=$string;");
var_dump($val);
?>
This will output int(31) which is the sum of the integers in the string
Related
i know this
$var1 = "10";
$var2 = "var1";
then
echo $$var2 gives us 10
i want to this with array
i have array
$intake_arr = array(5=>10,7=>20,8=>30,9=>40,10=>50,11=>60,12=>70);
i have some logic that will pick one array from set of array , all array will look like $intake_arr
if i do this $target_arr = "intake_arr";
then can $$target_arr[5] will yield 10? i tried but i didnt that 10 value, how can i achieve this with array
Your statement ($$target_arr[5]) is ambiguous. PHP doesn't know what you actually want to say: Do you mean: use $target_arr[5]'s value and prepend the $, to use that as a variable, or do you want to use the value of $target_arr, and get the fifth element of that array?
Obviously it's the latter, but PHP doesn't know that. In order to disambiguate your statement, you have to use curly braces:
${$target_arr}[5];
That'll yield 10. See the manual on variable variables for details
Note:
As people said in comments, and deleted answers: variable variables, like the one you're using is risky business. 9/10 it can, and indeed should be avoided. It makes your code harder to read, more error prone and, in combination with the those two major disadvantages, this is the killer: it makes your code incredibly hard to debug.
If this is just a technical exercise, consider this note a piece of friendly advice. If you've gotten this from some sort of tutorial/blog or other type of online resource: never visit that site again.
If you're actually working on a piece of code, and you've decided to tackle a specific problem using variable vars, then perhaps post your code on code-review, and let me know, I'll have a look and try to offer some constructive criticism to help you on your way, towards a better solution.
Since what you're actually trying to do is copying an array into another variable, then that's quite easy. PHP offers a variety of ways to do that:
Copy by assignment:
PHP copies arrays on assignment, by default, so that means that:
$someArray = range(1,10);//[1,2,3,4,5,6,7,8,9,10]
$foo = $someArray;
Assigns a copy of $someArray to the variable $foo:
echo $foo[0], ' === ', $someArray[0];//echoes 1 === 1
$foo[0] += 123;
echo $foo[0], ' != ', $someArray[0];//echoes 123 != 1
I can change the value of one of the array's elements without that affecting the original array, because it was copied.
There is a risk to this, as you start working with JSON encoded data, chances are that you'll end up with something like:
$obj = json_decode($string);
echo get_class($obj));//echoes stdClass, you have an object
Objects are, by default, passed and assigned by reference, which means that:
$obj = new stdClass;
$obj->some_property = 'foobar';
$foo = $obj;
$foo->some_property .= '2';
echo $obj->some_property;//echoes foobar2!
Change a property through $foo, and the $obj object will change, too. Simply because they both reference exactly the same object.
Slice the array:
A more common way for front-end developers (mainly, I think, stemming from a JS habbit) is to use array_slice, which guarantees to return a copy of the array. with the added perk that you can specify how many of the elements you'll be needing in your copy:
$someArray = range(1,100);//"large" array
$foo = array_slice($someArray, 0);//copy from index 0 to the end
$bar = array_slice($someArray, -10);//copy last 10 elements
$chunk = array_slice($someArray, 20, 4);//start at index 20, copy 4 elements
If you don't want to copy the array, but rather extract a section out of the original you can splice the array (as in split + slice):
$extract = array_splice($someArray, 0, 10);
echo count($someArray);//echoes 90
This removes the first 10 elements from the original array, and assigns them to $extract
Spend some time browsing the countless (well, about a hundred) array functions PHP offers.
${$target_arr}[5]
PHP: Variable variables
Try this one:
$intake_arr = array(5=>10,7=>20,8=>30,9=>40,10=>50,11=>60,12=>70);
$target_arr = 'intake_arr';
print ${$target_arr}[5]; //it gives 10
For a simple variable, braces are optional.But when you will use a array element, you must use braces; e.g.: ${$target_arr}[5];.As a standard, braces are used if variable interpolation is used, instead of concatenation.Generally variable interpolation is slow, but concatenation may also be slower if you have too many variables to concatenate.Take a look here for php variable variables http://php.net/manual/en/language.variables.variable.php
I have this variable $numbers and it contains values like this way-> 1,2,3,4,5
So when I echo this $number I naturally see like this-> 1,2,3,4,5
Now, Could you please tell me how to convert the variable "$number" like following
$topic=array("1","2","3","4","5");
You can just use explode which splits a string on a delimiter and returns an array. You don't need to add quotes around the numbers.
$topic = explode(',', $numbers);
lots of typos so hard to understand but I think you're talking about the fact the array made string datatypes when it made the array right? Everything else you already mention (but typo'd to death right?)
$number = array(1,2,3,4,5); //"1","2", are string litterals
foreach ($numbers as $number){
echo "<p>". $number . "</p>";
}
oh I see what he meant now - explode (used to be MUCH EASIER to use when it was called split - which is a better name IMO but has no reciprocal relationship to implode)
A string is an array of characters, correct? If so, then why does count() not produce the same result as strlen() on a string?
Unless it is an object, count casts its argument to an array, and
count((array) "example")
= count(array("example"))
= 1
A string is an array of characters in C, C++ and Java. In PHP, it is not.
Remember that PHP is a very loose language, you can probobly get a character from a PHP string with the []-selector, but it still dosn't make it an array.
count() counts the number of entries in an Array.
$test = array(1,2,3);
echo count($test);
Output: 3
Why would you want to use count() on a string when strlen() can do that? Are you not sure if your input is a string or an array? Then use is_array() to check that.
How exactly a string is being handled internally by a specific programming language, must not necessarily mean you can handle it equally to therefore "related" data types. What you describe may be possible in plain C. However PHP is not C and so is not following the same characteristics.
Strings are just a series of charactes, and count only counts number of elements in an array.
using $string[$index]; its just a shortcut kinda of thing to help you find Nth character,
you could use count(explode('',$string)); which presumably is what strlen does
so lesson for today is
count == array length
strlen == string length
count gets the number of elements in an array, srtlen gets the length of a string. This is in the docs:
http://php.net/manual/en/function.strlen.php
count is more preferabaly user for array value count
strlen its count only the no of char in str.....
eg. I want to replace instances of some words with their string length
"XXXX is greater than XX" becomes "4 is greater than 2"
Code that I intend to write :
$myStrings = Array("XX","XXX","XXXX","XXXXX");
$outStr = str_replace($myStrings,strlen(current($myStrings)),$outStr);
But here CURRENT is not working.
P.S. Please do not suggest workarounds to do this stuff since that is not what I intend to ask the forum. My query is getting current pointer to an array being traversed internally.
Thank You.
The function you are looking for is array_map. It applies a function to all elements of an array and outputs the results as a new array:
$myStrings = Array("XX","XXX","XXXX","XXXXX");
$outStr = str_replace($myStrings,array_map('strlen', $myStrings)),$outStr);
This might create a new problem as XXXX will be replaced with 22 before XXXX is checked. The solution to this would be reverse the input array:
$myStrings = array_reverse(Array("XX","XXX","XXXX","XXXXX"));
$outStr = str_replace($myStrings,array_map('strlen', $myStrings)),$outStr);
I don't think you can. Since it's an internal implementation, what would PHP expose to you that you could use to determine the current element?
Note that this is different from accessing internal array pointers using current(), key(), next(), reset() et al. I'm referring to the fact that PHP has an internal implementation of str_replace() for handling replacements of arrays of strings.
A quick test reveals that PHP doesn't even seem to bother with array pointers when replacing them with str_replace() anyway:
$arr = array('a', 'b', 'c'); // Internal pointer is at a
$str = 'abc';
next($arr); // Internal pointer is at b
echo str_replace($arr, 'x', $str), "\n"; // xxx
echo current($arr), "\n"; // b
Oh, by the way, this is what the manual for str_replace() says (strong emphasis mine):
If search is an array and replace is a string, then this replacement string is used for every value of search.
So specifically for str_replace(), I don't think it was ever intended for you to pass in a replacement string that is dynamic based on the input array.
And http://www.php.net/manual/de/function.array-walk.php isnĀ“t an option?
I am looking for the fastest way to remove duplicate values in a string separated by commas.
So my string looks like this;
$str = 'one,two,one,five,seven,bag,tea';
I can do it be exploding the string to values and then compare, but I think it will be slow. what about preg_replace() will it be faster? Any one did it using this function?
The shortest code would be:
$str = implode(',',array_unique(explode(',', $str)));
If it is the fastest... I don't know, it is probably faster then looping explicitly.
Reference: implode, array_unique, explode
Dealing with: $string = 'one,two,one,five,seven,bag,tea';
If you are generating the string at any point "up script", then you should be eliminating duplicates as they occur.
Let's say you are using concatenation to generate your string like:
$string='';
foreach($data as $value){
$string.=(strlen($string)?',':'').some_func($value);
}
...then you would need to extract unique values from $string based on the delimiter (comma), then re-implode with the delimiter.
I suggest that you design a more direct method and deny duplicates inside of the initial foreach loop, like this:
foreach($data as $value){
$return_value=some_func($value); // cache the returned value so you don't call the function twice
$array[$return_value]=$return_value; // store the return value in a temporary array using the function's return value as both the key and value in the array.
}
$string=implode(',',$array); // clean: no duplicates, no trailing commas
This works because duplicate values are never permitted to exist. All subsequent occurrences will be used to overwrite the earlier occurrence. This function-less filter works because arrays may not have two identical keys in the same array(level).
Alternatively, you can avoid "overwriting" array data in the loop, by calling if(!isset($array[$return_value])){$array[$return_value]=$return_value;} but the difference means calling the isset() function on every iteration. The advantage of using these associative key assignments is that the process avoids using in_array() which is slower than isset().
All that said, if you are extracting a column of data from a 2-dimensional array like:
$string='';
foreach($data as $value){
$string.=(strlen($string)?',':'').$value['word'];
}
Then you could leverage the magic of array_column() without a loop like this:
echo implode(',',array_column($str,'word','word'));
And finally, for those interested in micro-optimization, I'll note that the single call of array_unique() is actually slower than a few two-function methods. Read here for more details.
The bottomline is, there are many ways to perform this task. explode->unique->implode may be the most concise method in some cases if you aren't generating the delimited string, but it is not likely to be the most direct or fastest method. Choose for yourself what is best for your task.