Declare Array Inside Function Call PHP - php

Hey just wondering if there is a simpler way to declare an array inside a function call besides array()
$setup = new setupPage();
$setup->setup(array(
type => "static",
size => 350
));
class setupPage {
public function setup($config){
echo $config[size] . $config[type];
}
}
Thanks :D

If you use PHP 5.4+ you can use the shorthand, however it makes no difference in performance, but in actuality may make it harder to read:
$setup->setup(['type' => 'static',
'size' => 350]);

Create a PHP program with an array (student) with the following
categories: student_id, student_name, student_address,
student_state, student_zip, and student_age. A function within
the program will accept all the values and restrict the data type
passed for each. The function creates the array and place the
values into the array. Display the values in the array. Use try/catch
to display an error message if one or more of the values are not the
proper data type.

Related

How to get inserted document's id in transaction? (arangoDB)

I've been searching the web a lot for clues but can't seem to find any...
public function createNew($name, $type, $restriction,$picture){
global $connection;
$trans=new Transaction($connection,array( 'collections' => array( 'write' => array( 'group_relations','groups' ),'read'=> array( 'group_relations','groups' ) ), 'waitForSync' => true ));
$trans->setAction('function(){
var db= require("#arangodb").db;
var arr=db.groups.insert({"name":"'.$name.'","type":"'.$type.'","restriction":"'.$restriction.'","picture":"'.$picture.'"}).toArray();
db.group_relations.insert({"_from":"users/'.$_SESSION['uid'].'","_to":"groups/"+arr[0]["_id"],"status":"admin"});
}');
$trans->execute();
}
this is a PHP function that makes a transaction. In the transaction, I'm trying to create a group, get its id and insert it in the relation collection between the creator and the new group.
Basically make the creator of the group the admin.
"Fatal error: Uncaught triagens\ArangoDb\ServerException: 17 db.groups.insert(...).toArray is not a function".
Any solutions?
The result of insert({...}) is always an object. The result of insert([{...},{...},...,{...}]) is always an array. In either case .toArray() does not help.
So if you'd like to make sure, that you have an array as a result type, please use the array insert also for single entries:
var arr=db.groups.insert(
[{"name":"'.$name.'",
"type":"'.$type.'",
"restriction":"'.$restriction.'",
"picture":"'.$picture.'"}]);
So in order to get back the ids from your inserts only:
var ids = [];
db.groups.insert([{...},...,{...}]).forEach(
function(obj) {ids.push(obj._id)});
...

PHP - How do I add onto an array?

I have an existing array. I need to use array_push, or similar, to add a value onto the end of an array and assign it.
Code: http://pastebin.com/tNg7gZ91
array_push($playerHolo, 'player' => 'UsernameHere'); //invalid syntax (the =>)
var_dump($playerHolo);
I'm trying to add the value "player" and assign the string "UsernameHere" to it.
Other Information
array_push($playerHolo['1'], array('player' => 'UsernameHere'));
Displays
http://pastebin.com/GTDe8Ex9
Suggestions?
The second parameter must be an array using valid array syntax if it is an associative array:
array_push($this->playerHolo, array('player' => 'UsernameHere'));
array_push($this->playerHolo, ['player' => 'UsernameHere']);
But why don't you just use a simple assignment?
$this->playerHolo['player'] = 'UsernameHere';
You'll notice I used $this->playerHolo. This is because you are also using the wrong syntax for accessing class member variables. This will save you from the next error you will encounter.
You can do this in 2 ways:
array_push($playerHolo, array('player' => 'UsernameHere'));
or
$playerHolo['player'] = 'UsernameHere';

Symfony sfWidgetFormDoctrineChoice with multiple option on

I have created a form in which i embed another form. My question is about this embedded form - I'm using a sfWidgetFormDoctrineChoice widget with option multiple set to true. The code for this embedded form's configure method:
public function configure()
{
unset($this['prerequisite_id']);
$this->setWidget('prerequisite_id', new sfWidgetFormDoctrineChoice(array(
'model' => 'Stage',
'query' => Doctrine_Query::create()->select('s.id, s.name')->from('Stage s')->where('s.workflow_id = ?', $this->getOption('workflow_id') ),
'multiple' => true
)));
$this->setValidator('prerequisite_id', new sfValidatorDoctrineChoice(array(
'model' => 'Stage',
'multiple' => true,
'query' => Doctrine_Query::create()->select('s.id, s.name')->from('Stage s')->where('s.workflow_id = ?', $this->getOption('workflow_id') ),
'column' => 'id'
)));
}
I unset the prerequisite_id field because it is included in the base form, but I want it to be a multiple select.
Now, when I added the validator, everything seems to work (it passes the validation), but it seems like it has problems saving the records if there is more than one selection sent.
I get this PHP warning after submitting the form:
Warning: strlen() expects parameter 1 to be string, array given in
D:\Development\www\flow_dms\lib\vendor\symfony\lib\plugins\sfDoctrinePlugin\lib\database\sfDoctrineConnectionProfiler.class.php
on line 198
and more - I know, why - in symfony's debug mode I can see the following in the stack trace:
at Doctrine_Connection->exec('INSERT INTO stage_has_prerequisites
(prerequisite_id, stage_id) VALUES (?, ?)', array(array('12', '79'),
'103'))
So, what Symfony does is send to Doctrine an array of choices - and as I see in the debug sql query, Doctrine cannot render the query correctly.
Any ideas how to fix that? I would need to have two queries generated for two choices:
INSERT INTO stage_has_prerequisites (prerequisite_id, stage_id) VALUES (12, 103);
INSERT INTO stage_has_prerequisites (prerequisite_id, stage_id) VALUES (79, 103);
stage_id is always the same (I mean, it's set outside this form by the form in which it is embedded).
I have spend 4 hours on the problem already, so maybe someone is able to provide some help.
Well, I seem to have found a solution (albeit not the best one, I guess). Hopefully it'll be helpful to somebody.
Finally, after much thinking, I have concluded that if the problem comes from the Doctrine_Record not being able to save the record if it encounters an array instead of a single value, then the easiest solution would be to overwrite the save() method of the Doctrine_Record. And that's what I did:
class StageHasPrerequisites extends BaseStageHasPrerequisites
{
public function save(Doctrine_Connection $conn = null)
{
if( is_array( $this->getPrerequisiteId() ) )
{
foreach( $this->getPrerequisiteId() as $prerequisite_id )
{
$obj = new StageHasPrerequisites();
$obj->setPrerequisiteId( $prerequisite_id );
$obj->setStageId( $this->getStageId() );
$obj->save();
}
}
else
{
parent::save($conn);
}
}
(...)
}
So now if it encounters an array instead of a single value, it just creates a temporary object and saves it for each of this array's values.
Not an elegant solution, definitely, but it works (keep in mind that it is written for the specific structure of the data and it's just the effect of my methodology, namely See What's Wrong In The Debug Mode And Then Try To Correct It Any Way Possible).

recreating returned variables under the same name

I have a function that returns an array of variables. The variables it returns vary depending on what it needs to return. For example one time it could return array($pet,$color); and another time it could return array($height,$width,$table);
On the receiving end I want to make these variables available. If I knew I was expecting $pet and $color, I could do something like
list($pet, $color) = myfunction();
but I don't know what the function is going to return each time. So is there a way I could still recreate these variables under the same names when I receive the function output?
Edit: I was hoping to not have to do it by defining an associative array that has the name of the variable saved as a string in addition to the variable itself.
Does the function return an associative array, eg
return array(
'height' => $height,
'width' => $width,
'table' => $table
);
If so, you can then use the extract function to bring each entry into the current scope's symbol table
I think you need to use associative arrays instead, so entries will have fixed names associated with them:
array('height'=>$height, 'width'=>$width, 'table'=>$table)

use different string in function?

I am a total NOOB in programming (but this is only my second question on stackoverflow :-) ).
By a foreach function I get 5 different string values for $Loncoord, $Latcoord, $gui;
this I can see with the print_r in the code written below:
"-5.68166666667","+24.6513888889","IMG_3308",
But I now want to create 5 different markers in the $map->addMarkerByCoords (function is it ?).
print_r ("$Loncoord");
print_r ("$Latcoord");
print_r ("$gui");
$map->addMarkerByCoords("$Loncoord","$Latcoord","$gui",'OldChicago');
Is this possible?
Do I need to put them in a array and call these in the (function ?) or do I need to use a foreach function?
I tried both for a week now but I can't get it working.
Can you help me?
The answers you produced gave me a turn in the right direction.
Thank you for the quick responses and the explaining part.
But for the addMarkerByCoord (function! (stupid me)) I found this in the googlemaps API:
function addMarkerByCoords($lon,$lat,$title = '',$html = '',$tooltip = '') {
$_marker['lon'] = $lon;
$_marker['lat'] = $lat;
$_marker['html'] = (is_array($html) || strlen($html) > 0) ? $html : $title;
$_marker['title'] = $title;
$_marker['tooltip'] = $tooltip;
$this->_markers[] = $_marker;
$this->adjustCenterCoords($_marker['lon'],$_marker['lat']);
// return index of marker
return count($this->_markers) - 1;
}
It depends on the implementation of map::addMarkerByCoords()
The method (not a function) name, and its signature, suggests that you are only able to add one coord at a time. But to be sure you'ld need to know the methods true signature. So the question is: does the method allow arrays as arguments?
Usually, a method that allows you to add multiple items at once, has the plural name of the intended action in it's name:
map::addMarkersByCoords() // note the s after Marker
If the 'map' class is your own implementation, you are free to implement it the way you like of course, but in that case keep the descriptive names of the methods in mind. So, add one marker:
map::addMarkerByCoords()
Add multiple markers at once:
map::addMarkersByCoords()
Typically you would implement the plural method as something like this:
public function addMarkersByCoords( array $markers )
{
foreach( $markers as $marker )
{
$this->addMarkerByCoord( $marker[ 'long' ], $marker[ 'lat' ], $marker[ 'img ' ], $marker[ 'name' ] );
}
}
Basically, the plural method accepts one array, and adds each individual marker by calling the singular method.
If you wanna get even more OOP, you could implement the plural and singular method to accept (an array of) Marker objects. But that is not particalarly relevant for this discussion.
Also, the suggested expantion of the Map's interface with a plural method doesn't nessecarily mean you can't add multiple markers outside the object with calling the singular method in a foreach loop. It's up to your preference really.
If you want to call the addMarkerByCoords for 5 times with 5 different values for each parameter then you can build an array for every parameter and then iterate with the foreach function:
$Loncoord=array(1,2,3,4,5);
$Latcoord=array(1,2,3,4,5);
$gui=array(1,2,3,4,5);
$city=array('OldChicago','bla','bla','bla','bla');
foreach($Loncoord as $k=>$v)
$map->addMarkerByCoords($Loncoord[$k],$Latcoord[$k],$gui[$k],$city[$k]);
Try losing some of the quotes...
$map->addMarkerByCoords($Loncoord,$Latcoord,$gui,'OldChicago');
To answer the question properly though, we would need to know what addMarkerByCoords was expecting you to pass to it.

Categories