I feel stupid for asking this cause it seems so basic but it's really bugging me.
I have a method that returns an array with a single element. I just want it to return the element not wrapped in an array. I tried this.
return $f->getValue()[0];
and it gives an error but if I save it to a variable, it works fine.
$v = $f->getValue();
return $v[0];
I can't figure it out....
It's available only since PHP 5.4: http://codepad.viper-7.com/VHOW0o
What you are trying to do, is called array dereferencing, and is only possible in PHP as of version 5.4 (if you scroll up a few lines in the documentation article I linked to, you'll see it mentioned).
Use reset().
<?php return reset( $f->getValue() ); ?>
Edit: reset() is probably superior to current() as it also makes sure that the internal pointer is reset, despite it not making much difference if the array only contains one element.
As far as I know since you are returning an array you only can get an array. You can instead save the array to a variable in the class (accessible by $f->myArray) and then return just the string portion. Or the other option is to do what your second example is and return the array and retrieve the string from it.
have you tried this
<?php
return array_shift(array_values($array));
?>
Get the first element of an array
Related
I have a query string. For example:
?filters=1,2,3,4
It gets turned into an array:
$filters = explode(',', $_GET['filters']);
You could push a new value on
$filters = array_push($filters, $new->filter);
Then turn it into the query string
http_build_query($filters);
Or, remove a value
$filters = array_diff($filters, [$new->filter]);
Then turn it into the query string
http_build_query($filters);
I'm looking for an elegant solution to remove the item if it already exists or to add the item if it does not exist. Alternative solutions are also welcome.
Thank you.
Hopefully I'm understanding you correctly "I'm looking for an elegant solution to remove the item if it already exists or to add the item if it does not exist.". Also, not sure if it is elegant but may spark other ideas:
$filters = in_array($new->filter, $filters) ?
array_diff($filters, [$new->filter]) :
array_merge($filters, [$new->filter]);
That's about as elegant as it gets, unless you want to use PHP's array notation "hack", e.g.
?filters[]=1&filters[]=2&filters[]=3&etc...
^^---
That'd save you the explode() stage and gives you the ability to treat $_GET['filters'] as an array directly, but at the cost of an uglier/longer URL.
Perhaps you should write 2 functions, "remove" and "add", which would each loop through the array looking for the value in question. Then the remove function could remove it, and the add function could add it. The functions themselves would not be so elegant, but using them would be simple elsewhere in your code.
I've created an array from a PHP session variable, and now I'm trying to use ajax (within jQuery) to remove an element from the array.
I've got the following code so far:
$val = $_SESSION['enquiry-basket'];
$array = explode($val);
foreach ($enquiries as $a => $q) {
if ($q == $_POST['product_id']) {
unset($array[$a]);
}
}
The only problem is, it doesn't remove the item.
Can anyone explain why, and tell me how to fix it?
Edit
Sorry guys. The reason I mentioned jQuery is because I use a jQuery ajax call to process the PHP I displayed above.
The ajax query runs fine because it processes some javascript goodies (remove's a div from the HTML) once the ajax returns a success.I've added the delimiter (can't believe I missed it) but the element doesn't get removed from the array still.
I've never been good at multi-dimensional arrays, so here's the array printed:
Array ( [0] => 6 [1] => 8 )
It looks right to me, but I'm an amateur in arrays. (6 and 8 are of course my strings I inserted)
explode is missing the first argument:
explode(',', $val);
You are removing item from $array, not from $_SESSION['enquiry-basket'].
The explode function should have two parameters. But you given only the name of the array.
explode(separator,string,limit);
If I understand correctly what you are trying to do, the problem is that JQuery runs client side, which means that your PHP arrays on the server side disappear between each request from Ajax. The only array that remains is $_SESSION.
If you want to use AJAX, you need to remove from $_SESSION directly. Anything else is just useless because the arrays and variables "disappear" between each call.
Mostly an issue with the explode function, the second parameter is missing:
Change from:
$array = explode($val);
To:
$array = explode('~',$val); // ~ is a delimiter
I found myself using this:
$var=(string)array_shift(array_values($item->xpath($s)));
where $s is an xpath search string and the return is an array of objects that contain strings.
It works, but I'm not sure it's the best way to get the data I want.
I could use a tempvar, but I wanted to avoid that.
Any suggestions?
Careful with array_shift, as it will remove the element from the array stack, if you simply want the first value, you can use current:
$var = (string) current($item->xpath($s));
I believe this gives the same result.
$var=array_shift($item->xpath($s));
$var = $reset($item->xpath($s));
Note that this rewinds the array's internal pointer and returns the first element. The method current returns the element at the position the pointer happens to be in - it is not guaranteed to always be the first element.
Hey I have a problem with Simple DOM parser which is driving me nuts.
This works OK:
foreach($html->find('input[name=sex]') as $e)
echo $e->value;
Even if its only 1 result.
However this doesn't work:
echo $html->find('input[name=sex]')->value;
I don't want really use foreach because I expect only 1 result.
So someone could help me with second block of code?
Cheers
According to the docs, the second parameter is the index you wish to find. Set that to 0 to return the first (0th) element rather than an array of objects:
Find elements by the CSS selector. Returns the Nth element object if index is set, otherwise return an array of object.
$html->find('input[name=sex]', 0)->value;
$html->find('input[name=sex]')[0]->value;
It seems find returns an array so using index would help you.
Use the code above.
If you can use for-each on something, it is an array/collection, even if there is one element. You are asking to echo an entire array, for which which may need print_r. As another poster suggested, use a subscript.
I don't understand... I'm doing something and when I do print_r($var); it tells me that I have an array, so naturally I think I have an array yet when I do
if(is_array($xml->searchResult->item))
it returns false
I use this array with foreach(); in documentation it says that foreach() won't work with anything else but array, so assuming that this is an array that I'm working...
plus, if I try to access it via
echo $xml->searchResult->item[3];
i will get 4th element of my array
print_r will also print objects as though they are arrays.
well, is_array() returns true if your variable is an array, otherwise, it returns false. In your case, $xml->searchResult->item seems not to be an array. What is the output for
var_dump($xml->searchResult->item)
? Another hint: You can determine the type of a variable via gettype().
is_array() returns true only for real php arrays. It is possible to create a "fake" array by using the ArrayAccess class. That is, you can use normal array semantics (such as item[3]) but it is not a real array. I suspect your $item is an object. So use
if($x instanceof ArrayAccess || is_array($x))
Instead.
plus, if I try to access it via echo $xml->searchResult->item[3]; i will get 4th element of my array
That's right, the first element is always 0 unless you specifically change it.
The manual does mention that foreach works on objects as well, and it will iterate over properties.
In your case, the situation is slightly different because I guess you're using SimpleXML, which is yet another special case. SimpleXMLElement has its own iterator, which I assume is hardcoded as it doesn't seem to implement any of SPL's Iterator interfaces.
Long story short, some objects can be used as an array, but they are not one.
Just be careful to check what has been returned by your array. You might have an object with class or stdClass which is empty and you cannot get element from it.