How to translate multiple parameters to a PHP conditional if statement - php

Let's say I have the following url: example.php?grab=1,3&something=...
grab has two values, how can I translate that to a conditional if statement.
For example, if count is a variable and you want to calculate if count is equal to one of the grab values.
$grab = $_GET["grab"];
$count = 4;
if($count == $grab(values)) {
alert("True");
}

If its always going to be , that glues the values, just explode them, that turns them into an array. Then just use your resident array functions to check. In this example, in_array:
if(!empty($_GET['grab'])) {
$grab = $_GET["grab"];
$count = 4;
$pieces = explode(',', $grab);
if(in_array($count, $pieces)) {
// do something here if found
}
}
Sidenote: If you try to devise your url to be like this:
example.php?grab[]=1&grab[]=3&something
You wouldn't need to explode it at all. You can just get the values, and straight up use in_array.
The example above grab already returns it an array:
if(!empty($_GET['grab'])) {
$grab = $_GET["grab"];
$count = 4;
if(in_array($count, $grab)) {
// do something here if found
}
}

Method#1: Reformat URL and Use PHP in_array()
Why not reformat your url to something like this: example.php?grab[]=1&grab[]=3&something=... which automatically returns the grab value as an array in PHP?
And then do something like:
if(isset($_GET['grab']) && in_array(4, $_GET['grab'])) {
// do something
}
Method#2: Split String into Array and Use PHP in_array()
If you do not wish to reformat your url, then simply split the string into an array using php's explode function and check if value exists, for example:
if(isset($_GET['grab'])) {
$grab_array = explode(",", $_GET['grab'])
if(in_array(4, $grab_array)) {
// do something
}
}
Method#3: Use Regular Expressions
You could also use regular expressions to check for a match.

Related

Find the number of objects in a json array

I have searched a lot and I found few methods to find the length of my JSON array. I have tried:
count
json.length
but these return 1, instead of the actual length. I want to show it using PHP.
My json is:
$huge = '[{"location":[{"building":["Default Building"],"name":"Default Location"}],"name":"Default Organization"},{"location":[{"building":["test_loc1_building1","test_loc1_building2"],"name":"test location1"},{"building":["test_loc2_building2"],"name":"test location2"}],"name":"test Organization"}]';
How can I find the number of objects in my JSON array?
You need to decode the json object and then count the elements in it ..
$json_array = json_decode($json_string, true);
$elementCount = count($json_array);
You'll need to decode into PHP arrays before you do any work with the data.
Try:
$hugeArray = json_decode($huge, true); // Where variable $huge holds your JSON string.
echo count($hugeArray);
If you need to count to a lower depth, you'll need to iterate through the array.
For example, if you want to count the number of elements in the next layer, you can do:
foreach ($hugeArray as $key => $value) {
echo $key.' - '.count($value);
}
However, this isn't necessarily meaningful because it depends on what you are trying to count, what your goal is. This block only counts the number of elements 1 layer underneath, regardless of what the actual numbers could mean.
First decode your json and after that use count on it.
$huge='[{"location":[{"building":["Default Building"],"name":"Default Location"}],"name":"Default Organization"},{"location":[{"building":["test_loc1_building1","test_loc1_building2"],"name":"test location1"},{"building":["test_loc2_building2"],"name":"test location2"}],"name":"test Organization"}]';
$arr = json_decode($huge,true);
echo count($arr);
Object (an unordered collection of key:value pairs with the ':' character separating the key and the value, comma-separated and enclosed in curly braces; ...)
Wikipedia: JSON
So, all you have to do are just count opened curly braces.
substr_count($huge , '{');
But... If you are storing some strings with '{' in json you can't do it. In that way you have to write your own simple parser or regular expression.
But... the easies way to json_decode. And use recursive function if you want to get count of all objects in json.
function count_objects($value)
{
if (is_scalar($value) || is_null($value))
$count = 0;
elseif (is_array($value))
{
$count = 0;
foreach ($value as $val)
$count += count_objects($val);
}
elseif (is_object($value))
{
$count = 1;
$reflection_object = new \ReflectionObject($value);
foreach ($reflection_object->getProperties() as $property)
{
$count +=count_objects($property->getValue($value));
}
}
return $count;
}
$huge = '[{"location":[{"building":["Default Building"],"name":"Default Location"}],"name":"Default Organization"},{"location":[{"building":["test_loc1_building1","test_loc1_building2"],"name":"test location1"},{"building":["test_loc2_building2"],"name":"test location2"}],"name":"test Organization"}]';
echo count_objects(json_decode($huge));
We can use ".sizeof()" function.
So

Getting element from PHP array returned by function

I'm not sure if this is possible, but I can't figure out how to do it if it is...
I want to get a specific element out of an array that is returned by a function, without first passing it into an array... like this...
$item = getSomeArray()[1];
function getSomeArray(){
$ret = Array();
$ret[0] = 0;
$ret[1] = 100;
return $ret;
}
What's the correct syntax for this?
PHP cannot do this yet, it's a well-known limitation. You have every right to be wondering "are you kidding me?". Sorry.
If you don't mind generating an E_STRICT warning you can always pull out the first and last elements of an array with reset and end respectively -- this means that you can also pull out any element since array_slice can arrange for the one you want to remain first or last, but that's perhaps taking things too far.
But despair not: the (at this time upcoming) PHP 5.4 release will include exactly this feature (under the name array dereferencing).
Update: I just thought of another technique which would work. There's probably good reason that I 've never used this or seen it used, but technically it does the job.
// To pull out Nth item of array:
list($item) = array_slice(getSomeArray(), N - 1, 1);
PHP 5.4 has added Array Dereferencing,
here's the example from PHP's Array documentation:
Example #7 Array dereferencing
function getArray() {
return ['a', 'b', 'c'];
}
// PHP 5.4
$secondElement = getArray()[0]; // output = a
// Previously
$tmp = getArray();
$secondElement = $tmp[0]; // output = a
The syntax you're referring to is known as function array dereferencing. It's not yet implemented and there's an RFC for it.
The generally accepted syntax is to assign the return value of the function to an array and access the value from that with the $array[1]syntax.
That said, however you could also pass the key you want as an argument to your function.
function getSomeArray( $key = null ) {
$array = array(
0 => "cheddar",
1 => "wensleydale"
);
return is_null($key) ? $array : isset( $array[$key] ) ? $array[$key] : false;
}
echo getSomeArray(0); // only key 0
echo getSomeArray(); // entire array
Yes, php can't do that. Bat you can use ArrayObect, like so:
$item = getSomeArray()->{1};
// Credits for curly braces for Bracketworks
function getSomeArray(){
$ret = Array();
$ret[0] = 0;
$ret[1] = 100;
return new ArrayObject($ret, ArrayObject::ARRAY_AS_PROPS);
}
Okay, maybe not working with numeric keys, but i'm not sure.
I know this is an old question, but, in your example, you could also use array_pop() to get the last element of the array, (or array_shift() to get the first).
<?php
$item = array_pop(getSomeArray());
function getSomeArray(){
$ret = Array();
$ret[0] = 0;
$ret[1] = 100;
return $ret;
}
As the others says, there is no direct way to do this, I usually just assign it to a variable like so:
$items = getSomeArray();
$item = $items[1];
function getSomeArray(){
$ret = Array();
$ret[0] = 0;
$ret[1] = 100;
return $ret;
}
I am fairly certain that is not possible to do in PHP. You have to assign the returned array to another array before you can access the elements within or use it directly in some other function that will iterate though the returned array (i.e. var_dump(getSomeArray()) ).

Compare All strings in a array to all strings in another array, PHP

What i am trying to do is really but i am going into a lot of detail to make sure it is easily understandable.
I have a array that has a few strings in it. I then have another that has few other short strings in it usually one or two words.
I need it so that if my app finds one of the string words in the second array, in one of the first arrays string it will proceed to the next action.
So for example if one of the strings in the first array is "This is PHP Code" and then one of the strings in the second is "PHP" Then it finds a match it proceeds to the next action. I can do this using this code:
for ( $i = 0; $i < count($Array); $i++) {
$Arrays = strpos($Array[$i],$SecondArray[$i]);
if ($Arrays === false) {
echo 'Not Found Array String';
}
else {
echo 'Found Array String';
However this only compares the First Array object at the current index in the loop with the Second Array objects current index in the loop.
I need it to compare all the values in the array, so that it searches every value in the first array for the First Value in the second array, then every value in the First array for the Second value in the second array and so on.
I think i have to do two loops? I tried this but had problems with the array only returning the first value.
If anyone could help it would be appreciated!
Ill mark the correct answer and + 1 any helpful comments!
Thanks!
Maybe the following is a solution:
// loop through array1
foreach($array1 as $line) {
// check if the word is found
$word_found = false;
// explode on every word
$words = explode(" ", $line);
// loop through every word
foreach($words as $word) {
if(in_array($word, $array2)) {
$word_found = true;
break;
}
}
// if the word is found do something
if($word_found) {
echo "There is a match found.";
} else {
echo "No match found."
}
}
Should give you the result you want. I'm absolute sure there is a more efficient way to do this.. but thats for you 2 find out i quess.. good luck
You can first normalize your data and then use PHP's build in array functions to get the intersection between two arrays.
First of all convert each array with those multiple string with multiple words in there into an array only containing all words.
A helpful function to get all words from a string can be str_word_count.
Then compare those two "all words" arrays with each other using array_intersect.
Something like this:
$words1 = array_unique(str_word_count(implode(' ', $Array), 1));
$words2 = array_unique(str_word_count(implode(' ', $SecondArray), 1));
$intersection = array_intersect($words1, $words2);
if(count($intersection))
{
# there is a match!
}
function findUnit($packaging_units, $packaging)
{
foreach ($packaging_units as $packaging_unit) {
if (str_contains(strtoupper($packaging[3]), $packaging_unit)) {
return $packaging_unit;
}
}
}
Here First parameter is array and second one is variable to find

Can I generate an array based on url path?

I have a path like:
/blog/2/post/45/comment/24
Can I have an array depends on what I have on url, like :
$arr = array('blog'=>'2','post'=>'45','comment'=>'24');
But it should depend on variable passed:
/blog/2 should produce $arr = array('blog'=>'2');
Is this possible to create dynamic array?
You could try something like this:
function path2hash($path) {
// $path contains whatever you want to split
$chunks = explode('/', $path);
$result = array();
for ($i = 0; $i < sizeof($chunks) - 1; $i+=2)
$result[$chunks[$i]] = $chunks[$i+1];
return $result;
}
You could then use parse_url to extract the path, and this function to turn it into the desired hash.
First use $_SERVER['REQUEST_URI'] to find the current path.
now, you can use explode and other string functions to produce the array...
If you need a working example, Ill try and post one.
EDIT:
$path=explode('/',$path);
$arr=array(
$path[0]=>$path[1],
$path[1]=>$path[2]);
or don't know how long it is...
$arr=array();
for ($i=0; $i+1<count($path);i+=2)
$arr[$path[$i]]=$path[$i+1];
Here's a simple example trying to solve the issue. This will put the arguments in the "arguments" array, and will contain each combination of key/value in the array. If there's an odd number of arguments, the last element will be ignored.
This uses array_shift() to remove the first element from the array, which then is used as a key in the arguments array. We then remove the next element from the array, yet again using array_shift(). If we find an actual value here (array_shift returns NULL when the array is empty), we create a entry in the arguments array.
$path = '/blog/2/post/45/comment/24';
$elements = explode('/', $path);
// remove first, empty element
array_shift($elements);
$arguments = array();
while($key = array_shift($elements))
{
$value = array_shift($elements);
if ($value !== NULL)
{
$arguments[$key] = $value;
}
}
Not really an answer per se but you may find http://www.php.net/manual/en/function.parse-url.php useful.

Type check in all array elements

Is there any simple way of checking if all elements of an array are instances of a specific type without looping all elements? Or at least an easy way to get all elements of type X from an array.
$s = array("abd","10","10.1");
$s = array_map( gettype , $s);
$t = array_unique($s) ;
if ( count($t) == 1 && $t[0]=="string" ){
print "ok\n";
}
You cannot achieve this without checking all the array elements, but you can use built-in array functions to help you.
You can use array_filter to return an array. You need to supply your own callback function as the second argument to check for a specific type. This will check if the numbers of the array are even.
function even($var){
return(!($var & 1));
}
// assuming $yourArr is an array containing integers.
$newArray = array_filter($yourArr, "even");
// will return an array with only even integers.
As per VolkerK's comment, as of PHP 5.3+ you can also pass in an anonymous function as your second argument. This is the equivalent as to the example above.
$newArray = array_filter($yourArr, function($x) { return 0===$x%2; } );
Is there any simple way of checking if all elements of an array [something something something] without looping all elements?
No. You can't check all the elements of an array without checking all the elements of the array.
Though you can use array_walk to save yourself writing the boilerplate yourself.
You can also combine array_walk with create_function and use an anonymous function to filter the array. Something alon the lines of:
$filtered_array = array_filter($array, create_function('$e', 'return is_int($e)'))

Categories