Remove an item from an array? - php

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

Related

Exploding an array that may only have one value

I am not sure if this is doable or if its a bigger problem with in my code but I have a webpage where a user selects some values from a infinite amount. So for example there select a1 and b2 from my form.
The form then combines them so they become like this:
a1b1 or a1b1d1e1 as another example. I will then split these values up using an explode function. here is an fulll example
$v1 = a1**b1
$v2 = explode("**", $v1);
Now if the user only select one value, the explode doesnt seem to work as I dont get a value for $v2. EG
$v1 = a1
$v2 = explode("**", $v1);
Is there a way that I can get this to work? Im not sure why I don't even get a value coming out in the second example, just want to knwo if its a limitation with explode or wheter it may be something else.
Thank in advance for an help or guidance.
Ian
Sorry, not sure what the actual issue here is...
First:
<?php
var_dump(explode('**','A'));
This clearly shows that the explode() call works as expected, the output is:
array(1) {
[0] =>
string(1) "A"
}
Second:
If I get that right, then you get that data from a client side form where you invest effort into creating a string and then want to convert that into an array on the server side to work with it? Why? Simply hand it over as an array and all is good:
You can simply use a notation like myvalue[] on the client side and the form submission will result in an array $_POST['myvalue'] getting prepared on the server side you can use like any other array without the need to explode something first.
For ajax requests this is even easier, since you then will typically use JSON as transport format in your POST requests which supports arrays natively.

Return Array Element without Creating Variable

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

Passing multiple values from MYSQL/PHP table to jQuery

Basically, I have working solution for this, but I'm wondering if it could (should?) be done better in some other way.
I have table I'm creating in PHP with values from MYSQL. Each item in table has multiple values. In each line there is single link and clicking on this link fires up jQuery function. In each link there is also VALUE attribute with values from multiple MYSQL fields and joined with &&:
PHP code is:
foreach ($this->_data as $l)
{
?>
...
<td>Link</td>
...
<?php
}
And jQuery function to fire up when clickin' on link is:
$(".clickMe").click(function() {
myData = $(this).attr('value').split('&&');
});
Script splits string in VALUE attribute on && and creates an array myData with values:
myData[0] => value passed from $l->_data1 in PHP
myData[1] => value passed from $l->_data2 in PHP
Is this the right way to do it?
It's fine, as long as you'll never have && in your data. You could use json_encode() in PHP and then decode this into an array in JavaScript. That would be a more standard solution.
I would recommend against using && which looks like a boolean AND. Instead I would probably use something like a pipe to separate them val1|val2.
I think you're better off passing the whole joined string in to PHP and splitting it out there. It saves you work on both ends having to put the two resultant values into the proper post or get variables to send to PHP.
Then on the PHP side, it's a little easier to validate the one value's format before splitting it, as you can use a single regex like:
// Validate both values at once: 1 or more digits, a pipe, and one or more digits
if (preg_match('/^(\d+)\|(\d+)$/', $_POST['jqueryinput'])) {
// explode() and use in PHP...
list($val1, $val2) = explode("|", $_POST['jqueryinput']);
}

How to make a java script array from php array? [duplicate]

This question already has answers here:
Convert php array to Javascript
(21 answers)
Closed 9 years ago.
Iam using PHP,Smarty configuration.
Iam getting an array in PHP and sent it to tpl.I would like to make a javascript array in tpl from that php array.
PHP ARRAY
Array
(
[0] => Array
(
[dt] => 2011-12-02
[number] => 3
)
[1] => Array
(
[dt] => 2011-12-05
[number] => 3
)
[2] => Array
(
[dt] => 2011-12-07
[number] => 2
)
)
and I want to get it as a java script array in tpl
s1 = [[[2011-12-02, 3],[2011-12-05,3],[2011-12-07,2]]];
You'd have to loop through it to generate that array
<script>
var arr = [];
<?php foreach ($arr as $item) : ?>
arr.push(['<?php echo $item['dt']?>', <?php echo $item['number']?>]);
<?php endforeach; ?>
</script>
This will give you an array of arrays.
However, I would do it in another way. I'd just encode it with json and use it as an object
<script>
var data = <?php echo json_encode($arr)?>;
for (var x in data) {
//data[x].dt;
//data[x].number;
}
</script>
I really dislike the idea of inline PHP all over the place. We don't inline JavaScript or CSS these days because it's bad practice i.e. difficult to maintain. We appreciate separation of concerns. If you need to pass data from your application (PHP or otherwise) to JavaScript variables on the client side then there are two good mechanisms you can use. Either get the result as JSON via AJAX, or simply render the variables on the client side in a single accessible location.
Your templating engine should really be able to register the data on the page for you. What you are essentially doing is rendering a script, so your script include mechanism should take an optional argument for registering php variables. If you are not using a templating engine and only need to inject the variables, I guess it would be acceptable to do something along the lines of.
<script type="text/javascript">
var phpdata = <?php echo json_encode($phpdata)?>
</script>
Note that this is declaring a global. We are encouraged to avoid the usage of globals at all costs but I think it's a valid use case when sensibly chosen, such as if you register your own object in global scope as a sensible namespace, then refer to namespace.phpdata. Alternatively you simply wrap your JavaScript in an immediate function call and declare the variable in local scope.
function () {
var phpdata = <?php echo json_encode($phpdata)?>
...
}();
But like I said, in my opinion I think it's better to get your templating engine to handle it, so you pass the PHP data you need for each javascript include, and a single php data object is generated from this data and included in your page.
You can use the php function json_encode to encode the array to json and then use it as an array like object in javascript
First of all: The arrays are not equivalent.
$array = array_map('array_values', $array);
this one is equivalent to the one you want to see as JS-array
$js = json_encode($array);
If you want to keep the keys of the associative (inner) arrays, just omit the first expression.
If you want to do it in the smarty template, loop over your PHP array and output the javascript array elements, adding commas after every element except the last one.
s1 = [
{foreach from=$myArray item=item name=loop}
[{$item['dt']}, {$item['number']}] {if $smarty.foreach.loop.last == false},{/if}
{/foreach}
]
As other said, though - encoding the array as JSON in PHP seems much cleaner and easier way to do that.
first create a new javascript array:
var array = new array();
loop through the php array in your tpl and create the javascript array
foreach($phparray as $i => $ary) {
echo "array[".$i."] = new array(".$ary['dt'].",".$ary['number'].");
}
there are many ways of doing it. I believe there are a lot of solution in the internet.
basically u just need to use for-loops to acheive it
i have already googled it for you.
There

Variable in $_POST returns as string instead of array

In my form i have fields with name photoid[] so that when sent they will automatically be in an array when php accesses them.
The script has been working fine for quite some time until a couple days ago. And as far as i can remember i havent changed any php settings in the ini file and havent changed the script at all.
when i try to retrieve the array using $_POST['photoid'] it returns a string with the contents 'ARRAY', but if i access it using $_REQUEST['photoid'] it returns it correctly as an array. Is there some php setting that would make this occur? As i said i dont remember changing any php settings lately to cause this but i might be mistaken, or is there something else i am missing.
I had the same problem. When I should recieve array via $_POST, but var_dump sad: 'string(5) "Array"'. I found this happens, when you try use trim() on that array!
Double check your code, be sure you're not doing anything else with $_POST!
Raise your error_reporting level to find any potential source. It's most likely that you are just using it wrong in your code. But it's also possible that your $_POST array was mangled, but $_REQUEST left untouched.
// for example an escaping feature like this might bork it
$_POST = array_map("htmlentities", $_POST);
// your case looks like "strtoupper" even
To determine if your $_POST array really just contains a string where you expected an array, execute following at the beginning of your script:
var_dump($_POST);
And following for a comparison:
var_dump(array_diff($_REQUEST, $_POST));
Then verifiy that you are really using foreach on both arrays:
foreach ($_POST["photoid"] as $id) { print $id; }
If you use an array in a string context then you'll get "Array". Use it in an array context instead.
$arr = Array('foo', 42);
echo $arr."\n";
echo $arr[0]."\n";
​
Array
foo
$_POST['photoid'] is still an array. Just assign it to a variable, and then treat it like an array. ie: $array = $_POST['photoid'];
echo $array[0];

Categories